In this article, how do you write SQL WHERE clauses like the following when working with an ORM?
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
$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.
$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.
// 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
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.
📦