Laravel:多对多插入

问题描述 投票:0回答:2

我有两个型号,

User
Team
他们之间的关系是
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
数组中为每个成员创建一条记录。我该怎么做?

php laravel loops eloquent laravel-5.4
2个回答
52
投票

您应该将用户 ID 数组传递给

attach()
方法。

为了方便起见,

attach
detach
也接受 ID 数组作为输入

将代码更改为:

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

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

  $user->teams()->sync($teams);
Result pivot tabble:

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);
    }

© www.soinside.com 2019 - 2024. All rights reserved.