Laravel belongsToMany 自关联多对多关系配置详解
应用场景
以用户间的相互关注为例,系统需要记录这种社交关系。数据通常存储在 followers 表中,其中包含两个关键字段:follower_id 代表发起关注的用户 ID,followed_id 代表被关注的用户 ID。
在这种场景下,多对多关系不再遵循传统的 Model1、Model2 及连接表 Model1_Model2 的三张表结构。面对仅由单张中间表构成的自关联情况,需要在代码中重新声明这种特殊的多对多关系。
原理分析
在 Laravel 或其他主流框架中,标准的多对多关系通常由三个部分组成:第一个模型(Model1)、第二个模型(Model2)以及用于声明两者关系的中间表(Model1_Model2)。
然而,上述关注场景仅涉及两张表:User 模型自身和 followers 中间表。针对这种特殊情况,官方文档提供了支持方案,允许开发者自定义关联细节。
参考资料
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 方法支持灵活传参,以满足个性化关联需求。理解各参数的具体含义是正确配置的关键。
第一个参数指定关联的第二个模型类。
第二个参数指定中间表(关系表)的名称。
第三个参数指定第一个模型(即当前调用关系的模型)在中间表中的外键 ID 字段名。
第四个参数指定第二个模型(即被关联的模型)在中间表中的外键 ID 字段名。
解决方案
基于上述分析,我们可以推导出正确的配置方式。
在此场景中,第一个模型是 User,第二个模型也是 User,属于自关联。
中间表的名称确定为 'followers'。根据参数定义,需分别指定 follower_id 和 followed_id 对应的归属模型。
/**
* 关注当前用户的
* @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');
}
以上关于 Laravel 5.5 中 belongsToMany 自关联用法的解析即为全部内容,希望能提供有效参考。