場景
用戶之間相互關注,記錄這種關系的是followers表(follower_id 發起關注的人 followed_id被關注的人)
現在的多對多的關系就不再是傳統的三張表的關系了, 這種情況 多對多關系應該怎么聲明呢?
分析
laravel或者其他框架多對多的關系 一般都是由Model1 Model2 Model1_Model2(聲明兩者關系的表)來組成,
但是上面的場景 卻是只有兩張表,這時候就要研究下官方文檔了; 當然是支持的
參考資料
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方法傳遞的參數是可以定制的 以達到個性化的需求,
第一個參數是 第二個Model
第二個參數是 關系表名
第三個參數是 第一個Model在關系表中的外鍵ID
第四個參數是 第二個Model在關系表中的外鍵ID
解決
經過分析
1. 第一個Model是User 第一個Model也是User
2. 關系表名是 'followers'
/**
* 關注當前用戶的
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function followers()
{
return $this->belongsToMany(self::class, 'followers', 'followed_id','follower_id')->withTimestamps()
->withTimestamps();
}
/**
* 被當前用戶關注的用戶
*/
public function followed()
{
return $this->belongsToMany(self::class, 'followers', 'follower_id', 'followed_id');
}
以上這篇淺談laravel5.5 belongsToMany自身的正確用法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。