用Laravel同步或更新现有的pivot -如何根据第三个critria填充

时间:2022-03-19 09:25:56

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

我有3个表,用户/ users_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.

我通过users_types在用户和类型之间有一个belongToMany,其中包含一些信息。其中一个是表格中的行号。我试图基于userID和行号更新表,但不是基于typeID,后者由我的输入填充。

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).

但显然它不能工作,因为它想要的是类型id而不是line_number…我总是希望更新相同的line_number和userID。(我对每一行都有一个for循环)。

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.

哦,我试过同步……但是它给了我一个外键错误因为它发送的数字不应该在那里。

1 个解决方案

#1


10  

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

如果你想更新现有的pivot,你可以这样做:

$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.

第一个参数是以相关的模型id为键的数组,以及要更新的数据透视值数组,而第二个参数设置为false则表示不分离所有其他相关的模型。

#1


10  

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

如果你想更新现有的pivot,你可以这样做:

$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.

第一个参数是以相关的模型id为键的数组,以及要更新的数据透视值数组,而第二个参数设置为false则表示不分离所有其他相关的模型。