获取使用Doctrine查询构建器订购的所有实体

时间:2015-01-29 11:31:28

标签: php symfony doctrine

我对此感到有点疯狂。我有一个PhoneCodes实体,我只想检索一个字段排序的所有实体,所以没有条件,但我试图通过多种方式实现这一点,而不是工作。目前我有这个:

 $phonecodes = $this->getDoctrine()
->getRepository('AcmeDemoBundle:PhoneCodes')
->createQueryBuilder('p')
->orderBy('p.length', 'ASC')
->getQuery()
->getResult();

这样做的方法是什么?感谢。

2 个答案:

答案 0 :(得分:1)

您的代码应该是这样的:

$phonecodes = $this->getEntityManager()
        ->createQueryBuilder()
        ->select("p")
        ->from("AcmeDemoBundle:PhoneCodes", "p")
        ->orderBy("p.length", "ASC")
        ->getQuery()
        ->getResult()

答案 1 :(得分:1)

如果您在控制器中,请执行以下操作:

$phonecodes = $em->getRepository('AcmeDemoBundle:PhoneCodes')->findBy(
    array(),//conditions, none in this case
    array(//orderBy, multiple possible
        "length"=>"asc"
    )
);

这样您就不需要编写自定义存储库函数了。

如果您不想将其创建为存储库函数(例如在PhoneCodesRepository.php中),请按以下方式执行:

/**
 * Returns all phoneCodes hydrated to objects ordered by length
 * @param string $order - ASC | DESC
 * @return \Doctrine\Common\Collections\Collection
 */
function findAllOrderedByLength($order="ASC")
{
    $qb = $this->createQueryBuilder("p");

    $qb->orderBy("p.length", $order);

    return $qb->getQuery()->getResult();
}

http://symfony.com/doc/current/book/doctrine.html#custom-repository-classes

相关问题