2017-06-05 131 views
0

我想更新Laravel雄辯模型是這樣的。Laravel雄辯的模型更新根據字段值null或現有的條件

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 . "')") 
         ]); 
        }); 
       }); 

但它不工作。

換句話說,我想更新如下。

  • 如果 '理由' 爲空或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 
           ]); 
    
  • 其他

    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 . "')") 
           ]); 
    

    什麼是我的錯?我怎樣才能簡化陳述?請讓我知道〜

回答

1

這是錯誤的使用where功能的回調內部update功能

你必須這樣做,在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 . '")'), 
    ]); 
+0

謝謝!是否有可能將2個查詢合併爲一個? – Alex

+0

不,你可以玩耍,並將常見條件分配給一個變量,然後爲每個查詢克隆它併爲每個查詢添加自定義條件 – Aboudeh87

+0

Thanks @ Aboudeh87 – Alex