将 PSQL 表达式转换为 Laravel Eloquent 构建器表达式

Translating PSQL expression to Laravel Eloquent Builder expression

我正在尝试return一些结果集

PSQL 查询如下所示:

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

这 return 是正确的行集,不包括在 array_of_ids 中具有 id 的任何行,而且重要的是,不 return 任何 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");

但是结果是一样的

我做错了什么?

在你的 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");