【问题标题】:Laravel eloquent multiple whereNotInLaravel 雄辩的多个 whereNotIn
【发布时间】:2018-05-17 19:17:20
【问题描述】:

我正在尝试使用多个 whereNotIn 数组进行查询。由于某种原因,它们相互阻塞并忽略其他查询参数。

关于如何解决这个问题的任何线索?

$products = Products::orderBy('id','DESC')
    ->where('status', '=', 4)
    ->whereNotIn('category', $excluded)
    ->whereNotIn('location', ['New York', 'Boston', 'Washington, DC', 'Charlotte'])
    ->take(400)
    ->get();

【问题讨论】:

  • 你说的他们互相屏蔽是什么意思?
  • 例如,我得到了status不是4,并且没有排除category的产品。
  • 好的。使用->toSql() 代替->get()dd 结果。它会告诉你正在运行什么查询。
  • select * from products where status = ?和 category 不在 (?) 和 location 不在 (?, ?, ?, ?) 中,按 id desc 限制 400 排序
  • 确实很奇怪。 $excluded 的值是多少?不过,查询本身看起来不错。

标签: php sql laravel laravel-5 eloquent


【解决方案1】:

您需要在where 中对orWhereNotIn 进行分组以排除这两个条件,试试这个

$locations = ['New York', 'Boston', 'Washington, DC', 'Charlotte'];
$products = Products::orderBy('id','DESC')
->where('status', '=', 4)
->where(function($q) use ($locations,$excluded) {
    $q->orWhereNotIn('category', $excluded);
    $q->orWhereNotIn('location', $locations);
})
->take(400)
->get();

【讨论】:

  • 即使分组改变了任何东西(我不相信它会改变,因为 Eloquent 生成的查询看起来不错),我很确定 OP 需要 where 而不是 @987654326 @.
  • @lesssugar :假设您要排除州 [Saarland,Bavaria...] 或城市 [city1, city2,city3....] 但 OP 的查询是针对 [Saarland,Bavaria...] AND city [city1, city2,city3....] 排除您需要使用 orWhere
  • @user2486 如果是这种情况,那么您应该将答案中的orWhere 更改为普通的where,并将whereNotIn 改为or
  • 好吧,即使where not in 条件冲突,这也不能解释为什么如果他专门使用where status = 4,他会得到status 不是4 的产品。跨度>
  • @Teun 只需使用API docs 搜索您需要的任何内容。 :)
【解决方案2】:

$excluded 是一个数组吗?如果没有,你就可以了

->where('category', "<>", $excluded);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-03-14
    • 1970-01-01
    • 2017-10-17
    • 2019-06-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多