How to update a collection using Eloquent Laravel

你离开我真会死。 提交于 2019-12-09 04:40:34

问题


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


来源:https://stackoverflow.com/questions/25597266/how-to-update-a-collection-using-eloquent-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!