1. 程式人生 > >【laravel5.4】hasOne和belongsTo的區別

【laravel5.4】hasOne和belongsTo的區別

關聯關系 cti col body header func 就是 pro 模型

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的區別