I have a Symfony 3 project. And I am sending an array of varying length to a query builder. The query builder looks like this:
function findByQuery($sortBy) {
return $this->createQueryBuilder('d')
->leftJoin('d.cat', 'dc')
->leftJoin('d.dog', 'dd')
->leftJoin('d.rabbit', 'rr')
->getQuery()
->execute();
}
I want to use the $sortBy parameter to order the results. However the issue is that sometimes the $sortBy (which is an array) will sometimes only contain one element with a key and an order by setting (e.g. ASC or DESC), and other times will contain several keys. In either case I want to be able to sort the results by all the elements. Is there a simple way of doing this?
Many thanks,
This is as simple as:
$sortBy = [
'd.property1' => 'ASC',
'd.property2' => 'DESC'
];
function findByQuery(array $sortBy) {
// create QueryBuilder
$qb = $this->createQueryBuilder('d')
->leftJoin('d.cat', 'dc')
->leftJoin('d.dog', 'dd')
->leftJoin('d.rabbit', 'rr');
foreach ($sortBy as $property => $dir) {
$qb->addOrderBy($property, $dir);
}
return $qb->getQuery()
->execute();
}