Last active
June 8, 2016 14:44
-
-
Save pbowyer/3a32d79c65042795592d4ef8f89ee6dc to your computer and use it in GitHub Desktop.
Doctrine2 ordering question
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// I have a Doctrine2 Entity | |
// It has a 1 to Many relation with Meals, which in turn has a 1 to many relationship with MealDates | |
// If I run the following, the results are ordered correctly | |
$event = $doctrineRepository->find(42); | |
$qb = $this->_em->createQueryBuilder(); | |
$qb->select('m, md') | |
->from('Meal', 'm') | |
->leftJoin('m.mealDates', 'md') | |
->orderBy('md.date', 'ASC') | |
->addOrderBy('m.weighting', 'ASC') | |
->where('m.event = :event') | |
->setParameter('event', $event); | |
return $qb->getQuery()->getResult(); | |
// If I run the following, the results are NOT ordered correctly, and come out in the default database order: | |
$event = $doctrineRepository->find(42); | |
foreach ($event->getMeals() as $meal) { | |
foreach ($meal->getMealDates() as $mealDate) { | |
// Don't need to do anything - that call is enough to make the mealDates be ordered by the default database order | |
} | |
} | |
$qb = $this->_em->createQueryBuilder(); | |
$qb->select('m, md') | |
->from('Meal', 'm') | |
->leftJoin('m.mealDates', 'md') | |
->orderBy('md.date', 'ASC') | |
->addOrderBy('m.weighting', 'ASC') | |
->where('m.event = :event') | |
->setParameter('event', $event); | |
return $qb->getQuery()->getResult(); | |
// Is there a better way to fix this than using the clone keyword (which gives the correct order)? | |
$event = $doctrineRepository->find(42); | |
foreach ($event->getMeals() as $meal) { | |
$mealDates = clone $meal->getMealDates(); | |
foreach ($mealDates as $mealDate) { | |
// Now this doesn't affect ordering of the query below | |
} | |
} | |
$qb = $this->_em->createQueryBuilder(); | |
$qb->select('m, md') | |
->from('Meal', 'm') | |
->leftJoin('m.mealDates', 'md') | |
->orderBy('md.date', 'ASC') | |
->addOrderBy('m.weighting', 'ASC') | |
->where('m.event = :event') | |
->setParameter('event', $event); | |
return $qb->getQuery()->getResult(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment