0

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'

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You answer needs a bit of changes but it helped me out solving it. I will accept it as the right answer. The query should be like this $query = $this->_em->getRepository($entityName)->createQueryBuilder(' i ') and everything else is like your second part of the answer. Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.