问题
I am trying to update Laravel Eloquent model like this.
Res_Reservations::where('time_id', $time['id'])
->where('date', $bus['date'])
->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED'))
->where(function($query) use($time, $notesAdd) {
$query->whereNull('reason', function($query) use ($time, $notesAdd) {
return $query->update([
'time_id' => $time['move'],
'reason' => $notesAdd
]);
})
->orWhere('reason', '=', '', function($query) use ($time, $notesAdd) {
return $query->update([
'time_id' => $time['move'],
'reason' => $notesAdd
]);
})
->orWhere('reason', '<>', '', function($query) use ($time, $notesAdd) {
return $query->update([
'time_id' => $time['move'],
'reason' => DB::raw("CONCAT(reason, \r\n'" . $notesAdd . "')")
]);
});
});
But it does not working.
In other words, I want to update as below.
if 'reason' is null or emptystring
Res_Reservations::where('time_id', $time['id']) ->where('date', $bus['date']) ->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED')) ->update([ 'time_id' => $time['move'], 'reason' => $notesAdd ]);
else
Res_Reservations::where('time_id', $time['id']) ->where('date', $bus['date']) ->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED')) ->update([ 'time_id' => $time['move'], 'reason' => DB::raw("CONCAT(reason, '\r\n" . $notesAdd . "')") ]);
What is my mistake? And how can I make statements simpler? Please let me know~
回答1:
It is wrong to use update
function inside the callback of where
function
You have to do it in 2 queries like:
Res_Reservations::where('time_id', $time['id'])
->where('date', $bus['date'])
->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED'))
->where(function ($query
{
$query->where('reason', null)
->orWhere('reason', '');
})
->update([
'time_id' => $time['move'],
'reason' => $notesAdd,
]);
Res_Reservations::where('time_id', $time['id'])
->where('date', $bus['date'])
->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED'))
->where('reason', '!=', null)
->where('reason', '!=' '');
->update([
'time_id' => $time['move'],
'reason' => DB::raw('CONCAT(reason, "\r\n' . $notesAdd . '")'),
]);
来源:https://stackoverflow.com/questions/44379150/laravel-eloquent-model-update-according-to-condition-of-field-value-null-or-exis