如何在一个雄辩的查询中增加和更新列

问题描述 投票:5回答:2

是否可以更新时间戳(除了updated_at)并在一个查询中增加一列?我显然可以->increment('count')和单独的->update(['last_count_increased_at' => Carbon::now()]),但有一个简单的方法来做到这两个。

Product::where('product_id', $product->id) ->update(['count'=>count+1, 'last_count_increased_at' => Carbon::now()];

无需先查询并获取计数?

php eloquent laravel-5.2
2个回答
19
投票

您可以使用DB::raw方法:

Product::where('product_id', $product->id)
    ->update([
      'count'=> DB::raw('count+1'), 
      'last_count_increased_at' => Carbon::now()
    ]);

4
投票

您可以在操作期间指定要更新的其他列:

Product::where('product_id', $product->id)
->increment('count', 1, ['last_count_increased_at' => Carbon::now()]);
© www.soinside.com 2019 - 2024. All rights reserved.