【问题标题】:How to update all rows of a table without retrieving them in Laravel?如何更新表的所有行而不在 Laravel 中检索它们?
【发布时间】:2020-07-30 08:13:08
【问题描述】:

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

不应静态调用非静态方法 Illuminate\Database\Eloquent\Model::update()

我在迁移中这样做:

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

我正在向现有表“房间”添加一个 json 列“床”,并想设置默认值 ['One King', 'Two Doubles'],我想知道是否可以直接在查询中执行此操作而不加载模型。

我提出了以下解决方案,但感觉有点“hacky”:

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

有没有人知道在没有 where 语句的情况下更新所有行的另一种方法?

【问题讨论】:

  • 取决于服务器的配置,没有 where 子句你会得到一个错误

标签: mysql laravel eloquent laravel-6


【解决方案1】:

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

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

【讨论】:

  • 完美!我不敢相信我没有想到!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-11-16
  • 1970-01-01
  • 2020-11-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-03
相关资源
最近更新 更多