与 Laravel 同步或更新现有枢轴——如何根据第三个标准进行填充

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26059593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:10:54  来源:igfitidea点击:

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

phpmysqldatabaselaravellaravel-4

提问by commandantp

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

事情是这样的,我有 3 个表,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.

我通过 users_types 在用户和类型之间有一个belongToMany,其中包含一些信息的数据透视表。其中之一是表单中的行号。我正在尝试根据用户 ID 和行号而不是根据 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).

但显然它不会工作,因为它需要 typeID 而不是 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.

哦,我确实尝试过同步......但它给了我一个外键错误,因为它发送了不应该存在的数字。

回答by Jarek Tkaczyk

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 falsemeans, that you don't detach all the other related models.

第一个参数是以相关模型 ID 为键的数组,以及要更新的枢轴值数组,而第二个参数设置为false意味着您不会分离所有其他相关模型。