Reputation: 1763
I made a many-to-many relationship between my User and my Worker model. If a User adds a worker to his account, the Worker model gets attached to the user. This works just fine. But now I want to add a costum sort order each user can modify according to his needs (basically clicking up and down buttons in a table to move his workers up and down in the list). So I added a sort_id to my pivot table. But I struggle with setting the sort_id. I have 2 questions:
I attach the Worker to the User like this: $request->user()->workers()->attach($worker);
But how can I add the sort_id to the pivot table?
Upvotes: 1
Views: 224
Reputation: 25221
public function workers(){
return $this->belongsToMany('Worker')
->withPivot('sort_id')
->orderBy('pivot_sort_id','asc');
}
Then to edit the sort_id
$user->workers()->updateExistingPivot($workerId, ['sort_id'=>$newSortId]);
Upvotes: 2