使用 Doctrine query builder 获取所有实体

Get all entities ordered with Doctrine query builder

我对此有点抓狂。我有一个 PhoneCodes 实体,我只是想检索按字段排序的所有实体,所以没有 where 条件,但我试图通过多种方式实现这一点,但没有成功。目前我有这个:

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

有什么方法可以做到这一点?谢谢

你的代码应该是这样的:

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

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

$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