I have two models, User
and Team
The relationship between them is ManyToMany
:
In User
:
public function teamMembers(){ return $this->belongsToMany('App\Team')->withPivot('id');; }
And in Team
:
public function teamMembers(){ return $this->belongsToMany('App\User')->withPivot('id');; }
Now i want to add users to a specific team. So the pivot table name is team_user
.
Now the data i want to insert to pivot table is :
array:4 [▼ "_token" => "mlwoAgCQYals1N1s2lNa4U5OTgtMNHh9LUhNGrWh" "team_id" => "1" "members_id" => array:3 [▼ 0 => "2" 1 => "3" 2 => "4" ] "status" => "1" ]
What i am doing in my controller :
$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(); }
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 ?
hasMany relationship in laravel is used to create the relation between two tables. hasMany means create the relation one to Many. For example if a article have comments and we wanted to get all comments of the article then we can use hasMany relationship .
A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.
Eager loading is super simple using Laravel and basically prevents you from encountering the N+1 problem with your data. This problem is caused by making N+1 queries to the database, where N is the number of items being fetched from the database.
You should pass an array of user IDs to the attach()
method.
For convenience,
attach
anddetach
also accept arrays of IDs as input
Change your code to:
$team = \App\Team::findOrFail($request->team_id); $team->teamMembers()->attach($request->members_id);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With