Laravel:多次插入

时间:2017-01-31 04:56:49

标签: php laravel loops eloquent laravel-5.4

我有两个模型,UserTeam 它们之间的关系是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

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

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

1 个答案:

答案 0 :(得分:20)

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

  

为方便起见,attachdetach也接受ID数组作为输入

将您的代码更改为:

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