2017-06-05 43 views
0

現在我試圖更新Laravel雄辯模式是這樣的:與concate串Laravel更新數據庫,不能正常工作

   Res_Reservations::where('time_id', $time['id']) 
        ->where('date', $bus['date']) 
        ->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED')) 
        ->update(['time_id' => $time['move'], 'reason' => 'reason' . $notesAdd]); 

我要額外的字符串添加到下面的「理由」字段。

reason field = reason field + $ notesAdd;

但它不工作。它的行爲如下。

reason field ='reason'+ $ notesAdd;

我該如何解決?

回答

2

您可以通過使用raw expression而無需進行額外的查詢來做到這一點。

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, '" . $notesAdd . "')") 
       ]); 
+0

我更喜歡這個。希望我能想到它。 – Jason

+0

@treeface,非常感謝您的回覆。我還有一個問題。當原因字段爲空時,那麼CONCAT不起作用。請幫助更多! – Alex

+0

@Alex您可以使用mysql控制流功能:https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html。所以像'IF(理由IS NULL,NULL,CONCAT(原因,'無論'))'''' – treeface

0

最簡單的方法將需要您先加載記錄,以便它變成Laravel對象,然後更新屬性並保存記錄。

$record = Res_Reservations::where('time_id', $time['id']) 
       ->where('date', $bus['date']) 
       ->where('valid', config('config.TYPE_SCHEDULE_UNREMOVED'))->first(); 

$record->update(['time_id' => $time['move'], 'reason' => $record->reason . $notesAdd]);