如何使用 Eloquent Laravel 更新集合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25597266/
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
How to update a collection using Eloquent Laravel
提问by BenjaminRH
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
和Command
模型之间有一对多的关系(每个Device
都有很多commands
)。现在我想使用save()
方法更新一组命令。所以,我使用了以下代码:
$device = Device::find(1);
$commands = $device->commands()->whereStatus("pending")->get();
$commands->status = "sent";
$commands->save();
But I got a FatalErrorException
exception with an error message of Call to undefined method Illuminate\Database\Eloquent\Collection::save()
.
但是我收到了FatalErrorException
一个错误消息为Call to undefined method Illuminate\Database\Eloquent\Collection::save()
.
In other words, I am looking for an equivalent MySQL query of the following in the Eloquent
:
换句话说,我正在寻找以下内容的等效 MySQL 查询Eloquent
:
UPDATE commands SET status = 'sent' WHERE status = 'pending';
using Laravel 4.2
使用 Laravel 4.2
回答by BenjaminRH
You could try the update
method:
你可以试试这个update
方法:
$collection = $device->commands()->whereStatus("pending");
$collection->update(array("status" => "sent"));
回答by George Cummins
Since $commands
is a collection, changing the value of $commands->status
will not have the effect that you intend (setting the value of status
to 'sent' for every item in the collection).
由于$commands
是一个集合,更改 的值$commands->status
不会产生您想要的效果(将status
集合中的每个项目的值设置为“已发送”)。
Instead, act on each item in the collection independently:
相反,独立地对集合中的每个项目进行操作:
foreach ($commands as $command)
{
$command->status = 'sent';
$command->save();
}
You can also update the items in the database via Query Builder:
您还可以通过查询生成器更新数据库中的项目:
DB::table('your_table')->where('status', 'pending')->update(array('status' => 'pending'));