如何在没有where条件的情况下批量更新Eloquent模型?

时间:2017-12-05 03:26:45

标签: php laravel eloquent

我想用Eloquent模型的新值更新表中的所有行。 Laravel的文档提供了以下使用Eloquent进行批量更新的示例:

App\Flight::where('active', 1)
          ->where('destination', 'San Diego')
          ->update(['delayed' => 1]);

但我不需要那里的条件。理想情况下,我能够运行这样的东西:

App\Flight::update(['delayed' => 1]);

省略了where子句。但是这给出了错误:

PHP Deprecated:  Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically on line 1

如何使用Eloquent批量更新表格中的所有行?我希望尽可能避免使用DB::table('flights')->update(...)样式。

1 个答案:

答案 0 :(得分:1)

这可以通过运行

来完成
App\Flight::query()->update(['delayed' => 1]);

query()方法创建一个新的查询构建器实例,但没有任何初始子句(如where条件)。其他操作如update()可以在其后链接。