我尝试在 Laravel 中以多对多关系附加 2 个对象。所以我有用户和团队。当我尝试时,$user->teams()->attach($team->id, ['instrument_user_id' => $randomInstrument, 'is_leader' => $is_leader]);我得到了下一个错误:SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: team_members.user_id (SQL: insert into "team_members" ("team_id", "instrument_user_id", "is_leader") values (73, 1, 0))当我尝试时,$team->members()->attach($user->id, ['instrument_user_id' => $randomInstrument, 'is_leader' => $is_leader]);我得到了下一个错误:SQLSTATE[23000]: Integrity constraint violation: 19 NOT NULL constraint failed: team_members.team_id (SQL: insert into "team_members" ("user_id", "instrument_user_id", "is_leader") values (1, 1, 0))那么我必须在哪里添加我要附加的项目的 id,或者我做错了什么?用户型号:public function teams(){ return $this->belongsToMany('App\Team', 'team_members', 'team_id') ->as('details') ->withPivot('instrument_user_id', 'is_leader') ->using('App\TeamMember'); }团队模型:public function members() { return $this->belongsToMany('\App\User', 'team_members', 'user_id') ->as('details') ->withPivot('instrument_user_id','is_leader') ->using('App\TeamMember'); }
1 回答
慕的地6264312
TA贡献1817条经验 获得超6个赞
尝试这种关系:
团队模型:
public function teams(){
return $this->belongsToMany('App\Team', 'team_members', 'team_id', 'user_id')
->as('details')
->withPivot('instrument_user_id', 'is_leader')
->using('App\TeamMember');
}
团队模型:
public function members()
{
return $this->belongsToMany('\App\User', 'team_members', 'user_id', 'team_id')
->as('details')
->withPivot('instrument_user_id','is_leader')
->using('App\TeamMember');
}
- 1 回答
- 0 关注
- 103 浏览
添加回答
举报
0/150
提交
取消