English 中文(简体)
Laravel: 很多人插入
原标题:Laravel : Many to many insertion

I have two models, User and Team The relationship between them is ManyToMany:

在<代码>User:

public function teamMembers(){
    return $this->belongsToMany( AppTeam )->withPivot( id );;
}

载于Team:

public function teamMembers(){
    return $this->belongsToMany( AppUser )->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 = AppTeam::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_id and the first member_id. I want it to create one record per member from the members_id array. How am i gonna do that ?

最佳回答

您应将一系列用户识别资料通过attach(。 方法。

为方便起见,achdetach 并接受各种身份识别器作为投入

修改你的法典,以便:

$team = AppTeam::findOrFail($request->team_id);
$team->teamMembers()->attach($request->members_id);
问题回答
//
  $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);
    }





相关问题
Brute-force/DoS prevention in PHP [closed]

I am trying to write a script to prevent brute-force login attempts in a website I m building. The logic goes something like this: User sends login information. Check if username and password is ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

定值美元

如何确认来自正确来源的数字。

Generating a drop down list of timezones with PHP

Most sites need some way to show the dates on the site in the users preferred timezone. Below are two lists that I found and then one method using the built in PHP DateTime class in PHP 5. I need ...

Text as watermarking in PHP

I want to create text as a watermark for an image. the water mark should have the following properties front: Impact color: white opacity: 31% Font style: regular, bold Bevel and Emboss size: 30 ...

How does php cast boolean variables?

How does php cast boolean variables? I was trying to save a boolean value to an array: $result["Users"]["is_login"] = true; but when I use debug the is_login value is blank. and when I do ...

热门标签