Doctrine从最旧到最新分类获得10条最新记录

时间:2017-02-10 14:22:09

标签: sorting doctrine-orm symfony

我遇到了一个似乎不那么容易执行的简单请求 我想得到一张桌子的最后10条记录,所以我这样做了:

$records = $this->getDoctrine()
    ->getRepository('Bundle:Rec')
    ->findBy(array(), array('created' => 'DESC'), 10)
;

问题是记录将按降序排序 获得相同记录但按升序排列的最有效方法是什么?

2 个答案:

答案 0 :(得分:2)

您可以使用uasort对记录进行排序:

$records = $this->getDoctrine()
    ->getRepository('Bundle:Rec')
    ->findBy(array(), array('created' => 'DESC'), 10)
;

uasort($records, function ($first, $second) {
    return $first->getCreated() > $second->getCreated() ? 1 : -1;
});

答案 1 :(得分:0)

@Veve我已将您(已删除)的答案更改为:

$records = $this->getDoctrine()
        ->getRepository('Bundle:Rec')
        ->findBy(array(), array('created' => 'DESC'), 10)
;

$recCollection = new ArrayCollection($records);
$iterator = $recCollection->getIterator();
$iterator->uasort(function ($first, $second) {
    return $first->getCreated() > $second->getCreated() ? 1 : -1;
});

$measurements = $iterator;
相关问题