I need to insert or update a row that has created_at
and last_update
timestamps.
created_at
should only be set when the record is created while last_update
is updated whenever the record is updated.
I am not using Eloquent in this case, so I can't use methods like updateOrCreate()
. Also, using Query Builder's updateOrInsert()
won't work here as I must not change the value of created_at
.
This is how I ended up doing it:
$row = DB::table('some_table')
->where('last_update', '>=', now()->subMinutes(5))
->where('user_id', '=', $user_id)
->where('comment_type', '=', $comment_type)
->first();
if ($row === null) {
DB::table('some_table')->insert([
'user_id' => $user_id,
'comment_type' => $comment_type,
'created_at' => $created_at,
'last_update' => $last_update,
]);
} else {
DB::table('some_table')
->where('id', '=', $row->id)
->update(['last_update' => now()]);
}
Is it the right way to do it, or I can improve it to make it more performant?
Edit: Not only for performance, I just understood that my above code is not thread-safe and may cause some bad effects in certain cases. I wonder how can I change it to be thread-safe like Laravel's updateOrCreate()
/updateOrInsert()
.
$user_id
's in if block. \$\endgroup\$