如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 16:43:12  来源:igfitidea点击:

How to update a collection using Eloquent Laravel

laravellaravel-4

提问by BenjaminRH

I have a one to many relationship between Deviceand Commandmodels (each Devicehas many commands). Now I want to update a collection of commands using save()method. So, I used the following code:

我在DeviceCommand模型之间有一对多的关系(每个Device都有很多commands)。现在我想使用save()方法更新一组命令。所以,我使用了以下代码:

$device = Device::find(1);
$commands = $device->commands()->whereStatus("pending")->get();

$commands->status = "sent";
$commands->save();

But I got a FatalErrorExceptionexception 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 updatemethod:

你可以试试这个update方法:

$collection = $device->commands()->whereStatus("pending");
$collection->update(array("status" => "sent"));

回答by George Cummins

Since $commandsis a collection, changing the value of $commands->statuswill not have the effect that you intend (setting the value of statusto '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'));