佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > 淺談laravel5.5 belongsToMany自身的正確用法

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

熱門標(biāo)簽:Linux服務(wù)器 銀行業(yè)務(wù) 科大訊飛語音識別系統(tǒng) 阿里云 Mysql連接數(shù)設(shè)置 服務(wù)器配置 團購網(wǎng)站 電子圍欄

場景

用戶之間相互關(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)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • 基于laravel belongsTo使用詳解

標(biāo)簽:衡水 棗莊 廣元 蚌埠 江蘇 大理 衢州 萍鄉(xiāng)

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《淺談laravel5.5 belongsToMany自身的正確用法》,本文關(guān)鍵詞  ;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請?zhí)峁┫嚓P(guān)信息告之我們,我們將及時溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。
  • 相關(guān)文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    平果县| 三亚市| 新巴尔虎右旗| 抚顺县| 梁山县| 南召县| 台湾省| 山丹县| 滨州市| 英吉沙县| 江达县| 静安区| 康马县| 苍南县| 吴旗县| 东丽区| 嘉荫县| 铁力市| 安陆市| 阳东县| 定西市| 北安市| 斗六市| 杭锦后旗| 徐州市| 丹阳市| 远安县| 余干县| 尚义县| 德昌县| 中方县| 卢湾区| 威宁| 五华县| 乐清市| 阿瓦提县| 隆回县| 宜宾县| 临高县| 玉溪市| 海晏县|