I have two models, User
and Team
The relationship between them is ManyToMany
:
在<代码>User:
public function teamMembers(){
return $this->belongsToMany( AppTeam )->withPivot( id );;
}
载于Team
:
public function teamMembers(){
return $this->belongsToMany( AppUser )->withPivot( id );;
}
现在我想增加一个具体团队的用户。 因此,纸张名称为team_user
。
现在,数据要插入纸面表:
array:4 [▼
"_token" => "mlwoAgCQYals1N1s2lNa4U5OTgtMNHh9LUhNGrWh"
"team_id" => "1"
"members_id" => array:3 [▼
0 => "2"
1 => "3"
2 => "4"
]
"status" => "1"
]
在我的控制人员中,我做了些什么:
$team_id = $request->get("team_id");
$team = AppTeam::findOrFail($team_id);
foreach ($request->get( members_id ) as $key => $value) {
$team->teamMembers()->attach($team);
$team->save();
}
But it only inserts one record, I mean the team_id
and the first member_id
.
I want it to create one record per member from the members_id
array. How am i gonna do that ?