Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save onurkayaio/ec093cd69051f18d0273d6f2deb2f9b2 to your computer and use it in GitHub Desktop.
Save onurkayaio/ec093cd69051f18d0273d6f2deb2f9b2 to your computer and use it in GitHub Desktop.
Selecting the last record in a one-to-many relationship with DQL (Doctrine Query Language).
<?php
/**
* This example demonstrates how to join the last record in a
* one-to-many relationship using the Doctrine QueryBuilder.
*
* @author Ricard Derheim
*/
use Doctrine\ORM\Query\Expr;
// $entityManager instanceof EntityManager
$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder
->select('e, i')
->from('Entity', 'e')
->innerJoin('e.items', 'i')
->leftJoin('e.items', 'i2', Expr\Join::WITH, 'e = i2.property AND i.id < i2.id')
->where('i2.id IS NULL');
$query = $queryBuilder->getQuery();
$result = $query->getResult();
SELECT e, i
FROM Entity e
INNER JOIN e.items i
LEFT JOIN e.items i2
WITH e = i2.entity
AND i.id < i2.id
WHERE i2.id IS NULL
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment