代码之家  ›  专栏  ›  技术社区  ›  Robert Kujawa

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

  •  0
  • Robert Kujawa  · 技术社区  · 5 年前

    我试图更新某个数据库表中的所有行,但收到以下错误:

    不应静态调用非静态方法Illuminate\Database\elocquent\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();
        });
    }
    

    ['One King', 'Two Doubles'] ,我想知道是否可以在不加载模型的情况下直接在查询中执行此操作。

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

    有人知道没有where语句更新所有行的另一种方法吗?

    0 回复  |  直到 5 年前
        1
  •  3
  •   Brian Lee    5 年前

    你可以称之为静电 query()

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