quot;usortquot; a DoctrineCommonCollectionsArrayCollection?(“我们一个 DoctrineCommonCollectionsArrayCollection?)
问题描述
在各种情况下,我需要根据对象中的属性对 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.
希望有所帮助.
这篇关于“我们"一个 DoctrineCommonCollectionsArrayCollection?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“我们"一个 DoctrineCommonCollectionsArrayCollection?


基础教程推荐
- HTTP 与 FTP 上传 2021-01-01
- PHP 守护进程/worker 环境 2022-01-01
- 在 CakePHP 2.0 中使用 Html Helper 时未定义的变量 2021-01-01
- phpmyadmin 错误“#1062 - 密钥 1 的重复条目‘1’" 2022-01-01
- 如何在 Symfony 和 Doctrine 中实现多对多和一对多? 2022-01-01
- 找不到类“AppHttpControllersDB",我也无法使用新模型 2022-01-01
- 使用 PDO 转义列名 2021-01-01
- 在 yii2 中迁移时出现异常“找不到驱动程序" 2022-01-01
- 如何在 XAMPP 上启用 mysqli? 2021-01-01
- Doctrine 2 - 在多对多关系中记录更改 2022-01-01