【问题标题】:Use an array in Laravel update query在 Laravel 更新查询中使用数组
【发布时间】:2015-05-26 06:06:28
【问题描述】:

我想在 Laravel 更新查询的 Where 子句中推送一个数组。

这是更新查询。

DB::table('users')->where('id', 1)->update(array('votes' => 1));

是否可以使用如下查询??

$array_of_ids;
DB::table('users')->where($array_of_ids)->update(array('votes' => 1));

谢谢

【问题讨论】:

  • 使用whereIn更新

标签: php mysql sql laravel-5


【解决方案1】:

试试这个查询:

DB::table('users')->whereIn('id', $array_of_ids)->update(['votes' => 1]);

使用模型:

User::whereIn('id', $array_of_ids)->update(['votes' => 1]);

【讨论】:

    【解决方案2】:

    使用查询构建器:查询构建器还可以使用更新方法更新现有记录。 update 方法与 insert 方法一样,接受包含要更新的列的列和值对数组。您可以使用 where 子句限制更新查询:

    DB::table('users')
            ->where('id', 1)
            ->update(['votes' => 1]);
    

    【讨论】:

      【解决方案3】:

      只需使用whereIn:

      $array_of_ids;
      DB::table('users')->whereIn('id', $array_of_ids)->update(array('votes' => 1));
      

      请仔细阅读文档。在这种情况下,各种where 语句都记录在这里:Query Builder - Selects

      【讨论】:

      • 谢谢@lukasgeiter。但是这个查询更新了另一个也包含日期时间数据的字段。
      • 你确定吗?我很确定这个查询应该有效。究竟更新了什么?
      • 查询正在运行,但它还会更新另一个包含数据时间数据的字段。
      • 听起来你可能已经设置了数据库字段,以便在自动插入/更新时设置当前时间......
      猜你喜欢
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      • 2016-08-27
      • 2019-10-29
      • 2020-01-10
      • 2019-09-03
      • 2022-01-06
      • 2021-11-12
      相关资源
      最近更新 更多