laravel laravel4 更新数据透视表中的附加列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19083779/
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 08:29:58  来源:igfitidea点击:

laravel4 update additional columns in pivot table

laravellaravel-4eloquent

提问by Ray

I'm trying to update additional column data in a pivot table in a many to many relationship.

我正在尝试以多对多关系更新数据透视表中的其他列数据。

I have two tables - reservation and resource linked with a pivot table. I can attach and am working with the model. However I'm struggling to update one of the additional columns in the pivot table.

我有两个表 - 保留和资源与数据透视表链接。我可以附加并使用模型。但是,我正在努力更新数据透视表中的附加列之一。

I have an object: '$reservation' From that object I created another object $resources using:

我有一个对象:'$reservation' 从那个对象我创建了另一个对象 $resources 使用:

$resources = $reservation->resource()->get();

I'm then iterating through $resourcesusing a foreachloop as follows

然后我$resources使用foreach循环进行迭代,如下所示

foreach($resources as $resource ) {...}

I then want to update a column called gcal_id and am using the following:

然后我想更新一个名为 gcal_id 的列并使用以下内容:

$resource->pivot->gcal_id = "TEST";
$resource->save();

If I var_dump the model I can see the property exists to the correct value but in the database itself the entry is not being updated - so the save is not working

如果我 var_dump 模型,我可以看到属性存在于正确的值,但在数据库本身中,条目没有被更新 - 所以保存不起作用

I have the columns listed in both sides of the relationship with this:

我在与此关系的双方都列出了列:

->withPivot('start', 'end', 'quantity', 'product_id','gcal_id')

Given I have the resource object how can I update a column correctly in the pivot table and save to database?

鉴于我有资源对象,如何正确更新数据透视表中的列并保存到数据库?

Thanks

谢谢

回答by Matteus Hemstr?m

After that you set the attribute on the pivot:

之后,您在枢轴上设置属性:

$resource->pivot->gcal_id = "TEST";

You seem to save the resourceand not the pivot:

您似乎节省了资源而不是支点:

$resource->save();

If you want the pivot to be saved, saving the resource is not enough. Call save on the pivotinstead:

如果要保存pivot,仅保存资源是不够的。改为在枢轴上调用 save :

$resource->pivot->gcal_id = "TEST";
$resource->pivot->save();

回答by Wallace Maxters

An alternative instead of savemethod, is the method Illuminate\Database\Eloquent\Relations\BelongsToMany\updateExistingPivot()

替代save方法的替代方法是方法Illuminate\Database\Eloquent\Relations\BelongsToMany\updateExistingPivot()

$reservation->resource()->updateExistingPivot($resource_id, ['gcal_id' => 'TEST']);

Or

或者

$reservation->resource()->updateExistingPivot([1, 4, 5, 6], ['gcal_id' => 'TEST']);

This work for me in Laravel 4.2

这对我来说在 Laravel 4.2