淺談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)系的表)來組成,
但是上面的場(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)過分析
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自身的正確用法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
thinkphp框架page類與bootstrap分頁(美化)
這篇文章主要介紹了thinkphp框架page類與bootstrap分頁(美化) ,需要的朋友可以參考下2017-06-06
PHP統(tǒng)計(jì)nginx訪問日志中的搜索引擎抓取404鏈接頁面路徑
這篇文章主要介紹了PHP統(tǒng)計(jì)nginx訪問日志中的搜索引擎抓取404鏈接頁面路徑,可以對(duì)每個(gè)搜索引擎單獨(dú)統(tǒng)計(jì),需要的朋友可以參考下2014-06-06
PHP 實(shí)現(xiàn)從數(shù)據(jù)庫導(dǎo)出到.csv文件方法
這篇文章主要介紹了 PHP 實(shí)現(xiàn)從數(shù)據(jù)庫導(dǎo)出到.csv文件方法的相關(guān)資料,需要的朋友可以參考下2017-07-07
實(shí)例詳解PHP中html word 互轉(zhuǎn)的方法
這篇文章主要介紹了實(shí)例詳解PHP中html word 互轉(zhuǎn)的方法的相關(guān)資料,涉及到php html word互轉(zhuǎn)的相關(guān)知識(shí),本文介紹的非常詳細(xì),具有參考借鑒價(jià)值2016-01-01
codeigniter中實(shí)現(xiàn)一次性加載多個(gè)view的方法
這篇文章主要介紹了codeigniter中實(shí)現(xiàn)一次性加載多個(gè)view的方法,實(shí)例分析了codeigniter中view方法的實(shí)用技巧,需要的朋友可以參考下2015-03-03
laravel技巧之查詢構(gòu)造器Query Builder疊加鏈?zhǔn)秸{(diào)用的方法
這篇文章主要給大家介紹了關(guān)于laravel技巧之查詢構(gòu)造器Query Builder疊加鏈?zhǔn)秸{(diào)用的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友下面來一起看看吧。2017-12-12
PHP+ajaxfileupload+jcrop插件完美實(shí)現(xiàn)頭像上傳剪裁
在做項(xiàng)目的時(shí)候,經(jīng)常需要一些會(huì)員系統(tǒng)相關(guān)的內(nèi)容,比如頭像的上傳與裁剪等等,下面將這塊內(nèi)容分享給大家2014-06-06
PHP隨機(jī)獲取未被微信屏蔽的域名(微信域名檢測(cè))
這篇文章主要介紹了PHP隨機(jī)獲取未被微信屏蔽的域名(微信域名檢測(cè)),非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-03-03

