Does noone has any idea?
update / sync pivot table with multiple primary keys
Hello,
i have a problem to handle pivot table with more than 2 primary keys. I have three tables:
- posts
- users
- post_user
But in the post_user i want additional data, so i have:
- user_id
- post_id
- list_id ( in which list the post was sended )
- status
Normally you combine only the user_id and the post_id. How do i handle the other key? I have try the following:
$post_user = $user->posts()->where('list_id', '=', $list_id)->first();
$post_user->pivot->status = $request->input('status');
$post_user->pivot->save();
don't work (nothing has happened)
$post_user = PostUser::where('user_id', '=', $user_id)->where('post_id, '=', $post_id)->where('list_id', '=', $list_id)->first();
$post_user->status = $request->input('status');
$post_user->save();
don't work (Column not found: 1054 Unknown column 'id' in 'where clause' (SQL: update post_user set status = 1, updated_at = 2016-05-30 13:42:14 where id is null))
Is there a way to work with sync, something like:
$user->posts()->sync(['postid', 'listid'], ['status' => ...]);
i hope someone could help me
Take a look at the method updateExistingPivot
$user->roles()->updateExistingPivot($roleId, $attributes);
Documentation: https://laravel.com/docs/5.2/eloquent-relationships#inserting-many-to-many-relationships
However I do think you will still have issues here since you have two posts with the same id connected to the user but they are both in a different list. You probably need an extra where query here
Please or to participate in this conversation.