Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sync or updateExistingPivot with Laravel -- How to fill based on a 3rd critria

Here is the thing, I have 3 tables, users / users_types / types.

I have a belongToMany between users and types through users_types, the pivot with a few infos in it. One of them being the line number in a form. I am trying to update the table based on the userID and the line number but NOT on the typeID, the latter being filled by my inputs.

How can I make it happen? I have been trying

updateExistantPivot($line_number->line_number,array(
                                                        'type_id'  => $type_id,
                                                        'etc'             => $etc,
                                                        'duration'          => $duration
                                                    )
                                                );

But obviously it will not worked since it wants the typeID instead of the line_number... I always want to update the same line_number & userID. (I am in a for loop for every lines).

Thanks for your help!

oh, and I did try with a sync... but it gives me a foreign key error because it sends numbers that are not supposed to be there.

like image 348
commandantp Avatar asked Sep 26 '14 12:09

commandantp


1 Answers

If you want to update existing pivot, you can do this:

$model; // parent of the relation
$related; // related object already synced with the $model

$model->relation()->sync([$related->id => [ 'duration' => 'someValue'] ], false);

1st param is array with related model id as key, and array of pivot values to update, while 2nd param set to false means, that you don't detach all the other related models.

like image 125
Jarek Tkaczyk Avatar answered Sep 25 '22 02:09

Jarek Tkaczyk