How to update a collection using Eloquent Laravel

2020-05-25 07:57发布

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();

But I got a FatalErrorException exception with an error message of 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:

UPDATE commands SET status = 'sent' WHERE status = 'pending';

using Laravel 4.2

2条回答
叼着烟拽天下
2楼-- · 2020-05-25 08:28

You could try the update method:

$collection = $device->commands()->whereStatus("pending");
$collection->update(array("status" => "sent"));
查看更多
萌系小妹纸
3楼-- · 2020-05-25 08:46

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).

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'));
查看更多
登录 后发表回答