Reputation: 21
I need to update single matching record in db (PostgreSQL), but Limit method doesn't work with Update method. This code will update all records matching Where condition instead of single record.
DB::table("records")
->where('need_moderate','=','no')
->where('locked_per_time','<',$date_now->format("Y-m-d H:i:s"))
->limit(1)
->update(["locked_per_time"=>$locked_per->format("Y-m-d H:i:s"),'locked_by'=>$mdkey]);
How do I work around this so only single record would be updated?
Upvotes: 2
Views: 847
Reputation: 44526
Unlike with Oracle or MySQL update statements, using LIMIT
directly on PostgreSQL update statements is not possible. So chaining the limit(1)
method to the Query Builder instance does nothing, because the compileUpdate
method from Laravel's PostgresGrammar
class that is responsible for compiling the query, only compiles the where statements.
You could however overcome this by having a condition that uses a subquery which only returns one row that will be updated. Something like this should work:
DB::table("records")->whereIn('id', function ($query) use ($date_now) {
$query->from('records')
->select('id')
->where('need_moderate', '=', 'no')
->where('locked_per_time', '<', $date_now->format("Y-m-d H:i:s"))
->limit(1);
})->update(["locked_per_time" => $locked_per->format("Y-m-d H:i:s"), 'locked_by' => $mdkey]);
The whereIn('id', ...)
condition assumes your table has a column named id
that can be used as a unique identifier so it can find the first row that matches your conditions in the subquery.
Upvotes: 1