Doctrine DQL dynamic ORDER BY parameter

2020-03-06 05:09发布

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条回答
劳资没心,怎么记你
2楼-- · 2020-03-06 05:40

In that case use Doctrines Querybuilder:

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

$qb = $this->_em->createQueryBuilder();
$qb->select('t')
   ->from('Entities\Topic', 't')
   ->orderBy($order);
查看更多
登录 后发表回答