“我们"一个 DoctrineCommonCollectionsArrayCollection?

2022-01-03 00:00:00 php doctrine-orm

在各种情况下,我需要根据对象中的属性对 DoctrineCommonCollectionsArrayCollection 进行排序.没有找到立即执行此操作的方法,我这样做了:

In various cases I need to sort a DoctrineCommonCollectionsArrayCollection according to a property in the object. Without finding a method doing that right away, I do this:

// $collection instanceof DoctrineCommonCollectionsArrayCollection
$array = $collection->getValues();
usort($array, function($a, $b){
    return ($a->getProperty() < $b->getProperty()) ? -1 : 1 ;
});

$collection->clear();
foreach ($array as $item) {
    $collection->add($item);
}

当您必须将所有内容复制到本机 PHP 数组并返回时,我认为这不是最佳方法.我想知道是否有更好的方法来配置"DoctrineCommonCollectionsArrayCollection.我想念任何文档吗?

I presume this is not the best way when you have to copy everything to native PHP array and back. I wonder if there is a better way to "usort" a DoctrineCommonCollectionsArrayCollection. Do I miss any doc?

推荐答案

要对现有集合进行排序,您正在寻找 ArrayCollection::getIterator() 方法,该方法返回一个 ArrayIterator.例子:

To sort an existing Collection you are looking for the ArrayCollection::getIterator() method which returns an ArrayIterator. example:

$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
    return ($a->getPropery() < $b->getProperty()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));

最简单的方法是让存储库中的查询处理您的排序.

The easiest way would be letting the query in the repository handle your sorting.

假设您有一个 SuperEntity,它与 Category 实体存在多对多关系.

Imagine you have a SuperEntity with a ManyToMany relationship with Category entities.

然后例如创建这样的存储库方法:

Then for instance creating a repository method like this:

// Vendor/YourBundle/Entity/SuperEntityRepository.php

public function findByCategoryAndOrderByName($category)
{
    return $this->createQueryBuilder('e')
        ->where('e.category = :category')
        ->setParameter('category', $category)
        ->orderBy('e.name', 'ASC')
        ->getQuery()
        ->getResult()
    ;
}

...使排序变得非常容易.

... makes sorting pretty easy.

希望有所帮助.

相关文章