[英]Laravel Eloquent model update according to condition of field value null or existing
I am trying to update Laravel Eloquent model like this. 我正在尝试像这样更新Laravel Eloquent模型。
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 如果“原因”为null或为空字符串
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~ 请让我知道〜
It is wrong to use update
function inside the callback of where
function 在where
函数的回调内部使用update
函数是错误的
You have to do it in 2 queries like: 您必须在2个查询中执行此操作,例如:
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 . '")'),
]);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.