Home > Database > Mysql Tutorial > How to Execute a WHERE…IN Subquery Using Doctrine 2's Query Builder?

How to Execute a WHERE…IN Subquery Using Doctrine 2's Query Builder?

Linda Hamilton
Release: 2025-01-13 22:51:46
Original
175 people have browsed it

How to Execute a WHERE…IN Subquery Using Doctrine 2's Query Builder?

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>
Copy after login

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>
Copy after login

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!

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