As Tomaz answered above, it's not possible to create a UNION
using the createQueryBuilder
function but we can achieve it by using createNativeQuery
. Please check the below example,
public function firstQuery(array $filters) {
$qb = $this->em->createQueryBuilder()
->select('table1.numObject AS id, table1.name AS name')
->from("MyBundle:Table1", "table1");
return $qb->getQuery();
}
public function secondQuery(array $filters) {
$qb = $this->em->createQueryBuilder()
->select('table2.numObject AS id, table2.name AS name')
->from("MyBundle:Table2", "table2");
return $qb->getQuery();
}
// Main function
public function getAPIResult(array $filters, int $pageSize, int $page) {
$rsm = new ResultSetMappingBuilder($this->em);
$rsm->addScalarResult('id', 'id', 'integer');
$rsm->addScalarResult('id', 'name', 'string');
$sql = "SELECT * FROM (
({$this->firstQuery($filters)->getSQL()})
UNION ALL
({$this->secondQuery($filters)->getSQL()})
) tmp
ORDER BY name
LIMIT ? OFFSET ?
";
$query = $this->em->createNativeQuery($sql, $rsm);
$this->em->setParameter(1, $pageSize)
->setParameter(2, $pageSize * ($page-1));
return $query->getScalarResult();
}
Check official docs for Scalar Result:
https://www.doctrine-project.org/projects/doctrine-orm/en/2.15/reference/native-sql.html#scalar-results
Note: The above code snippet is not tested, please put a comment if face any issues.
Hope it helps. Happy coding ;)
<<<SQL
syntax? – Tirado