Laravel:多对多插入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41949911/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 15:14:05  来源:igfitidea点击:

Laravel : Many to many insertion

phplaravelloopseloquentlaravel-5.4

提问by Gammer

I have two models, Userand TeamThe relationship between them is ManyToMany:

我有两个型号,UserTeam他们之间的关系是ManyToMany

In User:

User

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

And in Team:

并在Team

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

Now i want to add users to a specific team. So the pivot table name is team_user.

现在我想将用户添加到特定团队。所以数据透视表名称是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();
}

But it only inserts one record, I mean the team_idand the first member_id. I want it to create one record per member from the members_idarray. How am i gonna do that ?

但它只插入一个记录,我的意思是team_id第一个member_id. 我希望它为members_id数组中的每个成员创建一个记录。我该怎么做?

回答by Alexey Mezenin

You should pass an array of user IDs to the attach()method.

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

For convenience, attachand detachalso accept arrays of IDs as input

为了方便起见,attach并且detach还接受ID的数组作为输入

Change your code to:

将您的代码更改为:

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