Laravel:多对多插入 [英] Laravel : Many to many insertion
问题描述
我有两个模型,User
和Team
它们之间的关系是ManyToMany
:
I have two models, User
and Team
The relationship between them is ManyToMany
:
在User
中:
public function teamMembers(){
return $this->belongsToMany('App\Team')->withPivot('id');;
}
在Team
中:
public function teamMembers(){
return $this->belongsToMany('App\User')->withPivot('id');;
}
现在,我想将用户添加到特定团队.因此,数据透视表的名称为team_user
.
Now i want to add users to a specific team. So the pivot table name is team_user
.
现在我要插入到数据透视表中的数据是:
Now the data i want to insert to pivot table is :
array:4 [▼
"_token" => "mlwoAgCQYals1N1s2lNa4U5OTgtMNHh9LUhNGrWh"
"team_id" => "1"
"members_id" => array:3 [▼
0 => "2"
1 => "3"
2 => "4"
]
"status" => "1"
]
我在控制器中正在做什么:
What i am doing in my controller :
$team_id = $request->get("team_id");
$team = \App\Team::findOrFail($team_id);
foreach ($request->get('members_id') as $key => $value) {
$team->teamMembers()->attach($team);
$team->save();
}
但是它只插入一条记录,我的意思是team_id
和第一个member_id
.
我希望它从members_id
数组为每个成员创建一条记录.我该怎么办?
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 ?
推荐答案
您应将用户ID数组传递给 attach()
方法.
You should pass an array of user IDs to the attach()
method.
为方便起见,
attach
和detach
还接受ID数组作为输入
For convenience,
attach
anddetach
also accept arrays of IDs as input
将您的代码更改为:
$team = \App\Team::findOrFail($request->team_id);
$team->teamMembers()->attach($request->members_id);
这篇关于Laravel:多对多插入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!