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

Ale*_*ris 9 php eloquent laravel-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()];

无需先查询并获取计数?

ayn*_*ber 26

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

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


小智 7

使用 Laravel 8,您现在可以在单个查询中实现此目的,以创建或更新重复键。

$values = [
    'name' => 'Something',
    'count' => 1,
];
$uniqueBy = ['name'];
$update = ['count' => DB::raw('count+1')];

Model::upsert($values, $uniqueBy, $update);
Run Code Online (Sandbox Code Playgroud)

如果模型存在count则增加,如果插入count则等于1。这是在数据库级别完成的,因此只涉及一个查询。

了解有关 upsert 的更多信息:https ://laravel.com/docs/8.x/eloquent#upserts


Ali*_*ani 6

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

Product::where('product_id', $product->id)
->increment('count', 1, ['last_count_increased_at' => Carbon::now()]);
Run Code Online (Sandbox Code Playgroud)

  • 谢谢,我不知道这个! (3认同)
  • 这感觉像是更雄辩的解决方案。 (3认同)