Laravel:多对多插入

29

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

User模型中:

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

团队中:

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数组中的每个成员创建一条记录。我该如何做到这一点?

2个回答

52

你应该向attach()方法传递一个用户ID数组。

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

将你的代码改为:

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

1
太好了,我只是忘记传递数组了。谢谢老兄。 - Gammer
5
@Alexey,还有一个sync选项,你可以更新答案以完善它,这只是一个建议。干杯! - Evis

0
//
  $user = User::find(1);
  $teams = [1,2,3,4];

  $user->teams()->sync($teams);

Result pivot team_user tabble: remember  (php artisan make:migration create_team_user_table) anphabet table name order

user_id : 1 1 1 1
team_id : 1 2 3 4

User Model:

 public function teams(): BelongsToMany
    {
        return $this->belongsToMany(Team::class);
    }

Team Model
public function users(): BelongsToMany
    {
        return $this->belongsToMany(User::class);
    }


关于你的方法的一些评论/解释会增加/改善你的答案。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接