laravel 如何为 Eloquent 数据透视表上的额外字段设置值

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

How can I set value for extra field on Eloquent pivot table

laravellaravel-4eloquent

提问by AxlSmith

$recourse->pivot->field = 'value';

$recourse->pivot->field = 'value';

gives error: Indirect modification of overloaded property

给出错误:间接修改重载的属性

回答by Jarek Tkaczyk

pivotis available only in the context of a relation:

pivot仅在关系的上下文中可用:

// won't work
$model = Model::first();
$model->pivot; // null

// will work
$anotherModel = AnotherModel::first();
$relatedModel = $anotherModel->relation()->first();
$relatedModel->pivot; // Pivot object

But for what you are trying to do simply use additional param in the savemethod:

但是对于您要执行的操作,只需在save方法中使用附加参数:

$product = Product::find($item->id);
$order->product()->save($product, ['price' => 12.34]);

For existing relation:

对于现有关系:

$product = $order->product()->find($productId);
$product->pivot->price = 12.34;
$product->pivot->save();

// or
$order->product()->updateExistingPivot($productId, ['price'=>12.34]);

And I suggest you use productsfor that kind of relation in order to make it easier to read.

我建议你使用products这种关系,以便于阅读。

回答by Carlo V

You should save() the pivot itself.

您应该 save() 枢轴本身。

$order->pivot->price = '1.234';
$order->pivot->save();