Reputation: 1506
I am using a custom FindBy filter where I want to pass orderBy and orderDirection as parameters like this:
public function findByFilter($filter, $orderBy = null, $orderDirection = null)
{
...
return $this->getEntityManager()->createQuery(
'SELECT i FROM ' . $entityName . ' i ' .
'WHERE i.id LIKE :id'
. ($orderBy) ? ' ORDER BY i.' . $orderBy : ''
. ($orderDirection) ? ' ' . $orderDirection : ''
)
->setParameter('id', $filter)
->getResult()
;
}
I am getting the following error message:
[Syntax Error] line 0, col 1: Error: Expected SELECT, UPDATE or DELETE, got 'ASC'
Upvotes: 0
Views: 1404
Reputation: 8268
Try this:
return $this->getEntityManager()->createQuery(
'SELECT i FROM ' . $entityName . ' i ' .
'WHERE i.id LIKE :id '
. ($orderBy ? ' ORDER BY i.' . $orderBy : '')
. ($orderDirection ? ' ' . $orderDirection : '')
)
->setParameter('id', $filter)
->getResult()
;
}
You were missing a space after ... :id
and the complete ternary operator has to be inside the braces.
Also There is a orderBy method:
public function findByFilter($filter, $orderBy = null, $orderDirection = null)
{
...
$query = $this->getEntityManager()->createQuery($entityName . ' i')
->where('i.id LIKE :id')
->setParameter('id', $filter);
if ($orderBy && $orderDirection) {
$query->orderBy('i.' . $orderBy . ' ' . $orderDirection);
}
return $query->getResult();
}
Code not tested but should work somehow this way. More info: https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/EntityManager.php#L287 and https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/Query.php
UPDATE: Ok sorry, I figured out that there is of course a slight difference between Query and queryBuilder. Query seems to be lacking the orderBy method.
Upvotes: 2