【问题标题】:Translating PSQL expression to Laravel Eloquent Builder expression将 PSQL 表达式转换为 Laravel Eloquent Builder 表达式
【发布时间】:2021-12-27 21:47:27
【问题描述】:

我正在尝试返回一些结果集

PSQL 查询如下所示:

SELECT DISTINCT id
FROM example
WHERE foo='abc'
AND (
  bar='x'
  OR
  bar='y'
)
AND NOT (
  id = ANY (array_of_ids)
);

这将返回正确的行集,不包括在array_of_ids 中具有 id 的任何行,但重要的是,不返回任何 bar=z 中的行

我已尝试使用 Eloquent 的查询构建器进行以下操作:

DB::table("example")
    ->where("example.foo", "=", "abc")
    ->whereNotIn("example.id", $array_of_ids)
    ->OrWhere(function($query) {
        $query->where("example.bar", "=", "x")
            ->where("example.bar", "=", "y");
    })
    ->distinct()
    ->select("example.id");

不幸的是,这既包括那些在 array_of_ids 中具有 id 的行,也包括不希望出现 bar=z 的行。

我已经尝试移动whereNotIn 调用所在的位置,如下所示:

DB::table("example")
    ->where("example.foo", "=", "abc")
    ->OrWhere(function($query) {
        $query->where("example.bar", "=", "x")
            ->where("example.bar", "=", "y");
    })
    ->whereNotIn("example.id", $array_of_ids)
    ->distinct()
    ->select("example.id");

但结果是一样的。

我做错了什么?

【问题讨论】:

    标签: laravel postgresql eloquent


    【解决方案1】:

    在你的 sql 中,我没有看到任何 or... 但是,or 应该只在 example.bar 比较中... 因此,要使用查询生成器获得相同的结果,我认为您的查询生成器应该如下所示:

     DB::table("example")
                ->where("example.foo", "=", "abc")
                ->where(function($query) {
                    $query->where("example.bar", "=", "x")
                        ->orWhere("example.bar", "=", "y");
                })
                ->whereNotIn("example.id", $array_of_ids)
                ->distinct()
                ->select("example.id");
    

    【讨论】:

    • 哦,非常感谢! SQL 查询AND ( bar='x' OR bar='y') 中有一个OR 子句——无论如何,您的查询生成器正是我所需要的。谢谢,我误解了orWhere 的功能。我会尽快接受你的回答。
    猜你喜欢
    • 2012-01-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多