【问题标题】:Eloquent build where query from arrayEloquent 构建 where 从数组查询
【发布时间】:2019-04-20 21:27:43
【问题描述】:

所以我正在尝试从关联数组中的数据准备一个 Eloquent 查询:

/* This works */
$this
    ->where("email", "me@gmail.com")
    ->where("is_active", 1)
    ->update($params);

/* This doesn't work */
$where = [
    'email' => "me@gmail.com",
    'is_active' => 1
];
foreach ($where as $k => $v) {
    $this->where("{$k}", "{$v}");
}
$this->update($params);

我错过了什么吗? 任何帮助表示赞赏。

编辑:查询不会更新数据库中的实体。

Ubuntu 18.10(宇宙墨鱼):4.18.0-17-generic x86_64 位:64 桌面:Gnome 3.30.2 拉拉多克,Laravel 5.8。

【问题讨论】:

  • 为什么$k$v 用引号括起来?
  • @dharman 表明我在测试期间尝试了几个版本;)

标签: php laravel orm eloquent


【解决方案1】:

它不起作用,因为每个$this->where() 都会实例化一个新的查询构建器,但从不执行它。

这行得通:

$where = [
    'email' => "me@gmail.com",
    'is_active' => 1
];

$query = $this->newQuery();

foreach ($where as $k => $v) {
    $query->where("{$k}", "{$v}");
}

$query->update($params);

您还可以将where() 与数组一起使用:

$this->where($where)->update($params);

【讨论】:

    【解决方案2】:

    我不太清楚你为什么需要这个。但是没有理由循环,你可以简单地将数组添加到 where 方法中。

    $this->where([
        'email' => "me@gmail.com",
        'is_active' => 1
    ])->update();
    

    【讨论】:

      猜你喜欢
      • 2016-03-30
      • 2019-09-06
      • 2017-01-07
      • 1970-01-01
      • 2020-12-10
      • 1970-01-01
      • 2020-03-19
      • 2018-07-28
      • 2021-08-17
      相关资源
      最近更新 更多