淺談laravel5.5 belongsToMany自身的正確用法
場(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è)參考,也希望大家多多支持腳本之家。
相關(guān)文章
PHP獲取當(dāng)前日期和時(shí)間及格式化方法參數(shù)
這篇文章主要介紹了PHP獲取當(dāng)前日期和時(shí)間及格式化方法參數(shù),本文先是講解了獲取當(dāng)前日期時(shí)間的方法,其后總結(jié)了格式化參數(shù),需要的朋友可以參考下2015-05-05PHP中使用register_shutdown_function函數(shù)截獲fatal error示例
這篇文章主要介紹了PHP中使用register_shutdown_function函數(shù)截獲fatal error示例,需要的朋友可以參考下2015-04-04PHP的Laravel框架結(jié)合MySQL與Redis數(shù)據(jù)庫(kù)的使用部署
這篇文章主要介紹了PHP的Laravel框架結(jié)合MySQL與Redis數(shù)據(jù)庫(kù)的使用部署,需要的朋友可以參考下2016-03-03PHP中關(guān)于PDO數(shù)據(jù)訪問(wèn)抽象層的功能操作實(shí)例
下面小編就為大家?guī)?lái)一篇PHP中關(guān)于PDO數(shù)據(jù)訪問(wèn)抽象層的功能操作實(shí)例。小編覺(jué)得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2017-09-09thinkphp5引入公共部分header、footer的方法詳解
小編做的項(xiàng)目需要在項(xiàng)目中需要用到引入公共導(dǎo)航、頭部、底部、右邊部分等等,接下來(lái)通過(guò)本文給大家介紹thinkphp5引入公共部分header、footer的方法 ,需要的朋友可以參考下2018-09-09解析php DOMElement 操作xml 文檔的實(shí)現(xiàn)代碼
本篇文章是對(duì)在php中DOMElement 操作xml 文檔的實(shí)現(xiàn)進(jìn)行了分析介紹。需要的朋友參考下2013-05-05使用PHP進(jìn)行微信公眾平臺(tái)開(kāi)發(fā)的示例
這篇文章主要介紹了使用PHP進(jìn)行微信公眾平臺(tái)開(kāi)發(fā)的示例,包括基本的微信平臺(tái)API調(diào)用和XML處理等,需要的朋友可以參考下2015-08-08