Laravel非默认约定多对多关联Pivot表配置问题
Laravel 自定义命名多对多关联配置补全
所有??位置的配置值按以下规则填写即可:
1. 中间表迁移补全
自定义中间表名为team_user_pivot,需要存储两个关联模型的外键,补全后代码如下:
class CreateUsersTeamTable extends Migration { protected $collection = "team_user_pivot"; /** * Run the migrations. * * @return void */ public function up() { Schema::create($this->collection, function (Blueprint $table) { $table->id(); $table->string('team_id'); // 存储团队表的关联主键_id值 $table->string('user_id'); // 存储用户表的关联主键_id值 $table->timestamps(); // 建议添加联合唯一索引,避免重复关联的脏数据 $table->unique(['team_id', 'user_id']); }); } }
2. 模型关联方法补全
Laravel的belongsToMany方法参数顺序固定为:belongsToMany(关联模型类, 中间表名, 当前模型在中间表的外键, 关联模型在中间表的外键, [当前模型本地键, 关联模型本地键])
Team模型关联方法
public function users() { // 未配置模型主键为_id时使用下方完整参数写法 // return $this->belongsToMany(User::class, 'team_user_pivot', 'team_id' , 'user_id', '_id', '_id'); return $this->belongsToMany(User::class, 'team_user_pivot', 'team_id' , 'user_id'); }
User模型关联方法
public function teams() { // 未配置模型主键为_id时使用下方完整参数写法 // return $this->belongsToMany(Team::class, 'team_user_pivot', 'user_id' , 'team_id', '_id', '_id'); return $this->belongsToMany(Team::class, 'team_user_pivot', 'user_id' , 'team_id'); }
注意事项
- 若未在User、Team模型中设置
protected $primaryKey = '_id';指定模型主键字段,必须使用注释中的完整参数写法,否则框架会默认读取id字段作为主键,导致关联查询失败。 - 若需要操作中间表的额外字段(如
timestamps生成的创建、更新时间),可以在关联方法后链式调用->withPivot(['created_at', 'updated_at'])获取对应字段值。
内容的提问来源于stack exchange,提问作者Logan
相关产品推荐
相关产品推荐

