【问题标题】:Laravel update database with concate string is not working带有连接字符串的 Laravel 更新数据库不起作用
【发布时间】:2017-06-06 05:58:21
【问题描述】:

现在我正在尝试像这样更新 Laravel Eloquent 模型:

                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]);

我想在“原因”字段中添加额外的字符串,如下所示。

原因字段 = 原因字段 + $notesAdd;

但它不起作用。它的作用如下。

原因字段 = '原因' + $notesAdd;

我该如何解决?

【问题讨论】:

    标签: laravel eloquent concatenation


    【解决方案1】:

    您可以通过使用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 . "')")
                    ]);
    

    【讨论】:

    • 我更喜欢这个。希望我能想到。
    • @treeface,非常感谢您的回复。我还有一个问题。当原因字段为空时,它的 CONCAT 不起作用。请提供更多帮助!
    • @Alex 你可以使用 mysql 控制流函数:dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html。所以像IF(reason IS NULL, NULL, CONCAT(reason, 'whatever'))
    • @treeface 谢谢。你能解释得更详细一点吗?请参阅stackoverflow.com/questions/44379150/…。现在我已经发布了更详细的问题。请回答这个问题。
    【解决方案2】:

    最简单的方法是先加载记录,使其成为 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]);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-24
      • 2010-10-03
      相关资源
      最近更新 更多