Laravel:多对多插入

14 浏览
0 Comments

Laravel:多对多插入

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

0