gpt4 book ai didi

php - 拉维尔 : Many to many insertion

转载 作者:IT王子 更新时间:2023-10-28 23:52:34 25 4
gpt4 key购买 nike

我有两个模型,UserTeam它们之间的关系是ManyToMany:

用户中:

public function teamMembers(){
return $this->belongsToMany('App\Team')->withPivot('id');;
}

Team 中:

public function teamMembers(){
return $this->belongsToMany('App\User')->withPivot('id');;
}

现在我想将用户添加到特定团队。所以数据透视表名称是 team_user

现在我要插入数据透视表的数据是:

array:4 [▼
"_token" => "mlwoAgCQYals1N1s2lNa4U5OTgtMNHh9LUhNGrWh"
"team_id" => "1"
"members_id" => array:3 [▼
0 => "2"
1 => "3"
2 => "4"
]
"status" => "1"
]

我在我的 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 数组中为每个成员创建一条记录。我该怎么做?

最佳答案

您应该将一组用户 ID 传递给 attach()方法。

For convenience, attach and detach also accept arrays of IDs as input

将您的代码更改为:

$team = \App\Team::findOrFail($request->team_id);
$team->teamMembers()->attach($request->members_id);

关于php - 拉维尔 : Many to many insertion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41949911/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com