Home > Database > Mysql Tutorial > How to Use a WHERE...IN Subquery with Doctrine 2's Query Builder?

How to Use a WHERE...IN Subquery with Doctrine 2's Query Builder?

Barbara Streisand
Release: 2025-01-13 21:54:47
Original
337 people have browsed it

How to Use a WHERE...IN Subquery with Doctrine 2's Query Builder?

Employing WHERE...IN Subqueries within Doctrine 2's Query Builder

This example demonstrates retrieving order items associated with orders containing a specific item, mirroring the functionality of an SQL query:

Equivalent SQL Query:

<code class="language-sql">SELECT DISTINCT i.id, i.name, order.name 
FROM items i 
JOIN orders o ON i.order_id=o.id 
WHERE o.id IN (
   SELECT o2.id FROM orders o2
   JOIN items i2 ON i2.order_id=o2.id AND i2.id=5
)
AND i.id != 5
ORDER BY o.orderdate DESC
LIMIT 10;</code>
Copy after login

Doctrine 2 Query Builder Implementation:

<code class="language-php"><?php // Access Doctrine's ExpressionBuilder
$expr = $em->getExpressionBuilder();

$qb = $em->createQueryBuilder();
$qb
    ->select(array('DISTINCT i.id', 'i.name', 'o.name'))
    ->from('Item', 'i')
    ->join('i.order', 'o')
    ->where(
        $expr->in(
            'o.id',
            $em->createQueryBuilder()
                ->select('o2.id')
                ->from('Order', 'o2')
                ->join('Item', 
                       'i2', 
                       \Doctrine\ORM\Query\Expr\Join::WITH, 
                       $expr->andX(
                           $expr->eq('i2.order', 'o2'),
                           $expr->eq('i2.id', '?1')
                       )
                )
                ->getDQL()
        )
    )
    ->andWhere($expr->neq('i.id', '?2'))
    ->orderBy('o.orderdate', 'DESC')
    ->setParameter(1, 5)
    ->setParameter(2, 5);</code>
Copy after login

Important Considerations:

  • Performance limitations might arise with Doctrine 2's handling of LIMIT clauses in subqueries.
  • While the IN clause conventionally expects an array, it also accommodates subqueries.
  • Reusing the same parameter for both id instances is recommended for consistency, although not strictly required.

The above is the detailed content of How to Use a WHERE...IN Subquery with Doctrine 2's Query Builder?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template