获取使用原则查询生成器订购的所有实体


Get all entities ordered with Doctrine query builder

我对此有点

疯狂。我有一个电话代码实体,我只想检索按字段排序的所有实体,所以没有 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