Symfony/doctrine - DQL 按参数排序未定义

Symfony/doctrine - DQL order by parameter not defined

谁能告诉我为什么这段代码不起作用:

$sort = 'u.username'; //test

$dql = 'SELECT u, p FROM GPAuthBundle:User u
    JOIN u.profile p
    WHERE ( u.username LIKE :username )
    AND ( u.username LIKE :search OR p.name LIKE :search )
    ORDER BY :sort ASC';

$parameters = array(
    'username' => '%'.$request->query->get('username').'%',
    'search' => '%'.$request->query->get('search').'%',
    'sort' => $sort
);

$query = $manager->createQuery($dql)->setParameters($parameters);

错误:

[Semantical Error] line 0, col 170 near ':sort ASC': Error: ':sort' is not defined.

您不能在 ORDER 中使用,因为 setParameters() 放了引号:ORDER BY "myvalue" ASC 而您想要 ORDER BY myvalue ASC

使用 PHP 变量,例如:

ORDER BY ' . $sort . ' ASC