Reputation: 6392
Is it possible to update a timestamp (besides updated_at
) and increment a column in one query? I obviously can
->increment('count')
and separately
->update(['last_count_increased_at' => Carbon::now()])
but is there an easy way to do both together.
Product::where('product_id', $product->id)
->update(['count'=> $count + 1, 'last_count_increased_at' => Carbon::now()];
Without having to query and get the count first?
Upvotes: 38
Views: 67954
Reputation: 4388
You can specify additional columns to update during the increment or decrement operation:
Product::where('id',$id)
->increment('count', 1, ['increased_at' => Carbon::now()]);
It is more eloquent solution.
Upvotes: 75
Reputation: 81
With Laravel 8 you can now achieve this in a single query to create or update on duplicate key.
$values = [
'name' => 'Something',
'count' => 1,
];
$uniqueBy = ['name'];
$update = ['count' => DB::raw('count+1')];
Model::upsert($values, $uniqueBy, $update);
If the model exists count
will be incremented, if it is inserted count
will equal 1
. This is done on the DB level, so only one query involved.
Read more about upserts: https://laravel.com/docs/8.x/eloquent#upserts
Upvotes: 7
Reputation: 23011
You can use the DB::raw
method:
Product::where('product_id', $product->id)
->update([
'count'=> DB::raw('count+1'),
'last_count_increased_at' => Carbon::now()
]);
Upvotes: 69