FORSMILE
JA
Symfony2021/05/12

Usage Examples of Doctrine's `andWhere` and `orWhere` [Symfony]

This article explains how to write SQL WHERE clauses like the one below when using an ORM.

← Back to Blog

In this article, how do you write SQL WHERE clauses like the following when working with an ORM?

text
WHERE foo = 1 AND (bar = 1 OR bar = 2)

Furthermore, I'd like to explain how to make the OR values and the number of nested levels variable in PHP.

WHEN CONDITIONS ARE DETERMINED IN ADVANCE

php
$q->where("foo = 1")
  ->andWhere("bar = 1 OR bar = 2");

This is simple; you just need to create an OR clause within `andWhere`.

HOW TO SPECIFY OR CLAUSE CONDITIONS FROM VARIABLES OR ARRAYS

Simply adding `orWhere` using an `if` statement will not result in the expected SQL.

php
$qb->where('foo = 1')
   ->andWhere($qb->expr()->orX(
      $qb->expr()->eq('bar', 1),
      $qb->expr()->eq('bar', 2)
   ));

Writing the first example using the `expr` class looks like the above.

Now, for the example above, I'd like to try getting the condition part from an array.

php
// tagList is array
$q->where("foo = 1");
$statements = $qb->expr()->orX();
foreach ($taglist as $tag) {
    $statements->add(
        $qb->expr()->eq('bar', $tag['id'])
    );
}
$qb->andWhere($statements);

From an array named `tagList`, I've assigned the numeric part to be compared as a variable.

SUMMARY

text
WHERE foo = 1 AND (bar = 1 OR bar = 2)

I thought this was a fairly simple structure, but writing it to be variable turned out to be quite tedious.

The `Expr` Class has other useful classes available, so please refer to the documentation.

Recommended Symfony Books

There aren't many varieties available, and since the framework itself contains a vast amount of information, even introductory books offer a lot to learn.

📦
Search Amazon US for related books and tools
Symfony PHP framework book
Search Amazon US → (affiliate link). As an Amazon Associate, we earn from qualifying purchases.
Related articles