如何更新 table 的所有行而不在 Laravel 中检索它们?

How to update all rows of a table without retrieving them in Laravel?

我正在尝试更新我的一个数据库 table 中的所有行,但我收到以下错误:

Non-static method Illuminate\Database\Eloquent\Model::update() should not be called statically

我正在迁移中执行此操作:

public function up()
{
    Schema::table('rooms', function (Blueprint $table) {
        $table->json('beds')->nullable();
    });

    Room::update([
        'beds' => ['One King', 'Two Doubles']
    ]);

    Schema::table('rooms', function (Blueprint $table) {
        $table->json('beds')->nullable(false)->change();
    });
}

我正在向我现有的 table 'rooms' 添加 json 列 'beds' 并想设置默认值 ['One King', 'Two Doubles'],我想知道如果我可以在不加载模型的情况下直接在查询中执行此操作。

我编了下面的方案,但是感觉有点"hacky":

// All id's are bigger than 0
Room::where('id', '>', 0)->update([
    'beds' => ['One King', 'Two Doubles']
]);

有谁知道另一种无需 where 语句即可更新所有行的方法?

您可以在模型上调用静态 query() 方法:

// ::query() return an instance of \Illuminate\Database\Eloquent\Builder
Room::query()->update([
  'beds' => ['One King', 'Two Doubles']
]);