1、從字面理解:假如A比B大,那么A hasOne B; B belongsTo A;
2、個人總結:
3、從代碼角度:
主要是看你是在哪一個model(模型)中編寫這個關聯關系,父關聯對象就是在父關聯model(本文是在Products的model類)下編寫的關聯模型。
has_one(或has_many):外鍵在子關聯對象中
//父關聯對象表
Products{
id
product_name
}
//子關聯對象表
Image{
image_id
img_name
product_id //foreign key
}
//hasOne方法的參數包括:
//hasOne('關聯模型名','外鍵名','主鍵名',['模型別名定義'],'join類型');
//默認的join類型為INNER
//寫在Products的model類中
public function Img(){
$this->hasOne('Image','product_id','id');
}
belongs_to:外鍵在你父聯對象中
//父關聯對象表:
Product{
product_id
img_id //foreignkey
product_name
}
//子關聯對象表
Image{
id
img_name
}
//belongsTo方法的參數包括:
//belongsTo(‘關聯模型名’,‘外鍵名’,‘關聯表主鍵名’,[‘模型別名定義’],‘join類型’);
//默認的join類型為INNER
//寫在Products的model類中
public function Img(){
$this->belongsTo('Image','img_id','id');
}
laravel5.4中hasOne和belongsTo、hasMany區分:
/*
* 下面三種寫法:第一種會報錯(前提:在Admin模型寫入users表的模型關系hasOne、belongsTo和hasMany)
* 因為User模型,我們並沒有寫入position的模型關聯方法
* 而Admin::XX 和new Admin 不報錯,因為寫入了position方法
*/
$users = new \App\Admin();
$uuu = User::find($this->user_id)->position->pos_name;
var_dump($uuu);
$users = new \App\Admin();
$uuu = $users::find($this->user_id)->position->pos_name;
var_dump($uuu);
$uuu = Admin::find($this->user_id)->department->dep_name;
var_dump($uuu);
//依據一個部門只能屬於一個公司,而一個部門卻可以有多個user,gogo
//$company_msg = Department::find(2)->company->company_name; //【一對一】、【多對一】 這種是正確的,別動了 $usernames = Department::find(6)->user() ->where('is_del','<>','1') ->pluck('username'); //一對多關系 $username_arr = []; foreach($usernames as $v){ $username_arr[] = $v; //輸出純一維數組 } var_dump($usernames); echo "<br>"; var_dump($username_arr);