Home >Database >Mysql Tutorial >How to Use a WHERE...IN Subquery with 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>
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>
Important Considerations:
LIMIT
clauses in subqueries.IN
clause conventionally expects an array, it also accommodates subqueries.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!