如何使用口才的Laravel更新集合 [英] How to update a collection using Eloquent Laravel
问题描述
我在Device
和Command
模型之间存在一对多的关系(每个Device
有很多commands
).现在,我想使用save()
方法更新命令集合.因此,我使用了以下代码:
I have a one to many relationship between Device
and Command
models (each Device
has many commands
). Now I want to update a collection of commands using save()
method. So, I used the following code:
$device = Device::find(1);
$commands = $device->commands()->whereStatus("pending")->get();
$commands->status = "sent";
$commands->save();
但是我出现了FatalErrorException
异常,错误消息为Call to undefined method Illuminate\Database\Eloquent\Collection::save()
.
But I got a FatalErrorException
exception with an error message of Call to undefined method Illuminate\Database\Eloquent\Collection::save()
.
换句话说,我正在Eloquent
中寻找以下的等效MySQL查询:
In other words, I am looking for an equivalent MySQL query of the following in the Eloquent
:
UPDATE commands SET status = 'sent' WHERE status = 'pending';
使用Laravel 4.2
using Laravel 4.2
推荐答案
您可以尝试update
方法:
$collection = $device->commands()->whereStatus("pending");
$collection->update(array("status" => "sent"));
这篇关于如何使用口才的Laravel更新集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!