最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

淺談laravel5.5 belongsToMany自身的正確用法

 更新時間:2019年10月17日 08:42:12   作者:cominglately  
今天小編就為大家分享一篇淺談laravel5.5 belongsToMany自身的正確用法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧

場景

用戶之間相互關(guān)注,記錄這種關(guān)系的是followers表(follower_id 發(fā)起關(guān)注的人 followed_id被關(guān)注的人)

現(xiàn)在的多對多的關(guān)系就不再是傳統(tǒng)的三張表的關(guān)系了, 這種情況 多對多關(guān)系應(yīng)該怎么聲明呢?

分析

laravel或者其他框架多對多的關(guān)系 一般都是由Model1 Model2 Model1_Model2(聲明兩者關(guān)系的表)來組成,

但是上面的場景 卻是只有兩張表,這時候就要研究下官方文檔了; 當(dāng)然是支持的

參考資料

https://laravel.com/docs/5.6/eloquent-relationships#many-to-many

In addition to customizing the name of the joining table, you may also customize the column names of the keys on the table by passing additional arguments to the belongsToMany method. The third argument is the foreign key name of the model on which you are defining the relationship, while the fourth argument is the foreign key name of the model that you are joining to:

belongsToMany方法傳遞的參數(shù)是可以定制的 以達(dá)到個性化的需求,

第一個參數(shù)是 第二個Model

第二個參數(shù)是 關(guān)系表名

第三個參數(shù)是 第一個Model在關(guān)系表中的外鍵ID

第四個參數(shù)是 第二個Model在關(guān)系表中的外鍵ID

解決

經(jīng)過分析

1. 第一個Model是User 第一個Model也是User

2. 關(guān)系表名是 'followers'

 /**
  * 關(guān)注當(dāng)前用戶的
  * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
  */
 public function followers()
 {
  return $this->belongsToMany(self::class, 'followers', 'followed_id','follower_id')->withTimestamps()
   ->withTimestamps();
 }

 /**
  * 被當(dāng)前用戶關(guān)注的用戶
  */
 public function followed()
 {
  return $this->belongsToMany(self::class, 'followers', 'follower_id', 'followed_id');
 }

以上這篇淺談laravel5.5 belongsToMany自身的正確用法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:

相關(guān)文章

最新評論

红河县| 噶尔县| 新营市| 剑河县| 长丰县| 桐梓县| 大关县| 东乡族自治县| 石林| 阳谷县| 涟水县| 友谊县| 龙口市| 崇州市| 哈巴河县| 石林| 长寿区| 大石桥市| 潜江市| 喀喇沁旗| 丹阳市| 柳河县| 九龙城区| 广州市| 洪洞县| 富源县| 漳州市| 常熟市| 磐石市| 新乐市| 上犹县| 云阳县| 宁河县| 新龙县| 梅河口市| 法库县| 兰坪| 武威市| 南昌市| 肇庆市| 浦江县|