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

但我得到了一个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:

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

使用Laravel 4.2

推荐答案

You could try the update method on the \Illuminate\Database\Eloquent\Builder object:

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

Laravel相关问答推荐

Laravel带S3存储器

Laravel模型嵌入嵌套模型时只附加属性

assertSee 由于 html 代码中的空格而失败

Laravel 验证 - 不同的属性规范

Laravel:子文件夹中的 lang 文件

Laravel:在失败时处理 findOrFail()

如何访问 Validator::extend 中的其他输入属性?

laravel 控制器中的全局变量

Laravel 5 日志(log)中的最大文件数

Laravel 5.1 是否与 PHP 7 兼容

Laravel 的 APP_ENV 变量(在 .env 文件中找到)是否有建议的值列表?

没有 index.php 的路由不起作用

Heroku 上的 Laravel 队列工作者

Laravel - 排序的集合输出不是数组

Laravel:如何在没有数据库的情况下对用户进行身份验证

Laravel 监听器监听多个事件

Laravel 无法创建根目录

扩展 Eloquent 的类的构造函数

如何在 Eloquent Orm 中实现自引用(parent_id)模型

如何在 Laravel 5 请求类中使用有时规则