How to update a collection using Eloquent Laravel

2020-05-25 07:49发布

问题:

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

回答1:

You could try the update method:

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


回答2:

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