Doctrine DQL dynamic ORDER BY parameter

2020-03-06 05:46发布

问题:

Im trying to pass the ORDER BY column as a parameter in DQL, like below:

$this->em->createQuery("SELECT t FROM Entities\Topic t ORDER BY :order")
     ->setParameters( array('order' => 't.name') )->getResult();

I guess it doesn't work because setParameter will escape :order, however the below solution doesn't seem very good:

$order = 't.name'; // Dynamic value
$this->em->createQuery("SELECT t FROM Entities\Topic t ORDER BY $order")
     ->getResult();

Is there a better way to solve this?

回答1:

In that case use Doctrines Querybuilder:

$order = 't.name'; // Dynamic value

$qb = $this->_em->createQueryBuilder();
$qb->select('t')
   ->from('Entities\Topic', 't')
   ->orderBy($order);