如何在Laravel中自动将值添加到现有值?

4

如何使用我的模型在 Laravel Eloquent ORM 中运行此 SQL 语句?

update products set quantity = quantity + 3

请阅读文档:https://laravel.com/docs/5.8/database#running-queries - ceejayoz
1个回答

5

首先,您需要获取要更改的特定实例:

$product = Product::find($id);

现在,您拥有对象的所有属性,并且可以更改已加载的值:

$product->quantity += 3;

最后,您必须保存更改:

$product->save();

然后,如果您检查数据库,该值将被更改。

附注:使用Eloquent。


4
这里最好使用$product->increment('quantity', 3)。参考链接:https://laravel.com/docs/5.8/queries#increment-and-decrement。 - ceejayoz

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接