Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Translating PSQL expression to Laravel Eloquent Builder expression

I am trying to return some result set

The PSQL query looks like this:

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

This returns the correct set of rows, not including any rows that have an id in the array_of_ids but also, importantly, does not return any rows where bar=z

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

I’ve attempted the following with Eloquent’s query builder:

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");

Unfortunately, this both includes those rows that have an id in the array_of_ids, and also includes rows where bar=z which is undesired.

I’ve tried moving where the whereNotIn call is, as follows:

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");

But the result is the same.

What am I doing wrong?

>Solution :

in your sql, I do not see any or
however, or should be in example.bar comparison only …
so, to get the same result using Query Builder, I think your query builder should look like:

 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");
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading