濮阳杆衣贸易有限公司

主頁(yè) > 知識(shí)庫(kù) > 淺談laravel5.5 belongsToMany自身的正確用法

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

熱門標(biāo)簽:電銷招聘機(jī)器人 格陵蘭島地圖標(biāo)注 天津營(yíng)銷電話機(jī)器人加盟代理 地圖標(biāo)注入哪個(gè)科目 福泉電話機(jī)器人 太原極信防封電銷卡 熱線電話機(jī)器人 南寧crm外呼系統(tǒng)平臺(tái) 事業(yè)單位如何百度地圖標(biāo)注

場(chǎng)景

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

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

分析

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

但是上面的場(chǎng)景 卻是只有兩張表,這時(shí)候就要研究下官方文檔了; 當(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á)到個(gè)性化的需求,

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

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

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

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

解決

經(jīng)過(guò)分析

1. 第一個(gè)Model是User 第一個(gè)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自身的正確用法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

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

標(biāo)簽:佳木斯 郴州 通化 阿克蘇 寶雞 金華 香港 自貢

巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《淺談laravel5.5 belongsToMany自身的正確用法》,本文關(guān)鍵詞  淺談,laravel5.5,belongsToMany,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問(wèn)題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無(wú)關(guān)。
  • 相關(guān)文章
  • 下面列出與本文章《淺談laravel5.5 belongsToMany自身的正確用法》相關(guān)的同類信息!
  • 本頁(yè)收集關(guān)于淺談laravel5.5 belongsToMany自身的正確用法的相關(guān)信息資訊供網(wǎng)民參考!
  • 推薦文章
    荔波县| 安徽省| 项城市| 新乡市| 呈贡县| 宾川县| 琼中| 福贡县| 石首市| 青田县| 晋州市| 清丰县| 富源县| 扬中市| 奇台县| 东兰县| 黄骅市| 定南县| 黄平县| 黑龙江省| 玉门市| 庄浪县| 比如县| 平罗县| 崇文区| 葵青区| 迁安市| 西畴县| 东源县| 祁东县| 涿州市| 贺州市| 东海县| 葫芦岛市| 宜丰县| 嘉善县| 怀来县| 上饶县| 麻江县| 疏附县| 二连浩特市|