-
-
Save Microtribute/9798512deccc24de37d6958fcf32391a to your computer and use it in GitHub Desktop.
Doctrine: Union with JOIN example
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 | |
namespace AppBundle\Repository; | |
use AppBundle\Entity\Country; | |
use AppBundle\Entity\CountryTranslation; | |
use Doctrine\ORM\EntityRepository; | |
use Doctrine\ORM\Query\ResultSetMapping; | |
use Doctrine\ORM\QueryBuilder; | |
class CountryRepository extends EntityRepository | |
{ | |
/** | |
* @return Country[] | |
*/ | |
public function getSelectList() | |
{ | |
$qbs = []; | |
$qbs[] = $this->createQueryBuilder('c') | |
->addSelect('t') | |
->leftJoin('c.translations', 't') | |
->where('c.code = ?1') | |
->orderBy('c.name', 'ASC'); | |
$qbs[] = $this->createQueryBuilder('c') | |
->addSelect('t') | |
->leftJoin('c.translations', 't') | |
->where('c.eu = ?2') | |
->orderBy('c.name', 'ASC'); | |
$qbs[] = $this->createQueryBuilder('c') | |
->addSelect('t') | |
->leftJoin('c.translations', 't') | |
->where('c.eu = ?3') | |
->orderBy('c.name', 'ASC'); | |
$rsm = new ResultSetMapping(); | |
$rsm | |
->addEntityResult($this->getClassName(), 'c') | |
->addFieldResult('c', 'id_0', 'id') | |
->addFieldResult('c', 'name_1', 'name') | |
->addFieldResult('c', 'code_2', 'code') | |
->addFieldResult('c', 'eu_3', 'eu') | |
->addJoinedEntityResult(CountryTranslation::class, 't', 'c', 'translations') | |
->addFieldResult('t', 'id_4', 'id') | |
->addFieldResult('t', 'locale_5', 'locale') | |
->addFieldResult('t', 'field_5', 'field') | |
->addFieldResult('t', 'content_7', 'content') | |
; | |
$query = $this->getEntityManager()->createNativeQuery($this->unionQueryBuilders($qbs), $rsm); | |
$query | |
->setParameter(1, 'FR') | |
->setParameter(2, true) | |
->setParameter(3, false); | |
return $query->getResult(); | |
} | |
/** | |
* @param array $queryBuilders | |
* | |
* @return string | |
*/ | |
private function unionQueryBuilders(array $queryBuilders) | |
{ | |
$imploded = implode(') UNION (', array_map(function (QueryBuilder $q) { | |
return $q->getQuery()->getSQL(); | |
}, $queryBuilders)); | |
return '('.$imploded.')'; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment