Leveraging Doctrine 2's Query Builder for WHERE…IN Subqueries
This guide demonstrates how to construct a Doctrine 2 query to select unique order items containing a specific item. The equivalent SQL query is:
<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>
Here's how to replicate this using Doctrine 2's query builder:
<code class="language-php">/** @var Doctrine\ORM\EntityManager $em */ $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', $qb->createSubquery() ->select('o2.id') ->from('Order', 'o2') ->join('o2.items', 'i2') // Assuming a proper relationship ->where($expr->eq('i2.id', '?1')) ->getDQL() ) ) ->andWhere($expr->neq('i.id', '?2')) ->orderBy('o.orderdate', 'DESC') ->setMaxResults(10) // Use setMaxResults for LIMIT ->setParameter(1, 5) ->setParameter(2, 5); $query = $qb->getQuery(); $results = $query->getResult();</code>
This improved query builder code uses a subquery more efficiently. It assumes a correctly defined relationship between Order
and Item
entities. setMaxResults(10)
is used instead of relying on potential subquery limitations. Remember that the entities Item
and Order
must exist within your Doctrine 2 mappings. Thorough testing is still recommended to handle potential edge cases.
The above is the detailed content of How to Execute a WHERE…IN Subquery Using Doctrine 2's Query Builder?. For more information, please follow other related articles on the PHP Chinese website!