在各种情况下,我需要根据对象中的属性对Doctrine\Common\Collections\ArrayCollection
进行排序。如果没有立即找到方法,我会这样做:
// $collection instanceof Doctrine\Common\Collections\ArrayCollection
$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数组并返回时,这不是最好的方法。我想知道是否有更好的方法来“使用”Doctrine\Common\Collections\ArrayCollection
。我想念任何文件吗?
答案 0 :(得分:87)
要对现有Collection进行排序,您要查找返回ArrayIterator的 ArrayCollection :: getIterator()方法。例如:
$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
return ($a->getPropery() < $b->getProperty()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));
最简单的方法是让存储库中的查询处理您的排序。
想象一下,你有一个与类别实体具有ManyToMany关系的SuperEntity。
然后例如创建一个这样的存储库方法:
// 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()
;
}
...使排序变得非常简单。
希望有所帮助。
答案 1 :(得分:44)
自Doctrine 2.3起,您可以使用Criteria API
例如:
<?php
public function getSortedComments()
{
$criteria = Criteria::create()
->orderBy(array("created_at" => Criteria::ASC));
return $this->comments->matching($criteria);
}
注意:此解决方案需要公开访问
$createdAt
属性或公共getter方法getCreatedAt()
。
答案 2 :(得分:20)
如果您有ArrayCollection字段,则可以使用注释进行订购。例如:
说一个名为Society的实体有许多许可证。你可以用
/**
* @ORM\OneToMany(targetEntity="License", mappedBy="society")
* @ORM\OrderBy({"endDate" = "DESC"})
**/
private $licenses;
这将按照desc顺序通过endDate(datetime字段)对ArrayCollection进行排序。
请参阅Doctrine文档:http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#orderby
答案 3 :(得分:0)
文档准则不允许按属性对相关对象进行排序。
如果要这样做(像我一样),则必须像以前的响应一样使用Iterator的uasort
方法,如果使用PHP 7,则可以使用Spaceship运算符<=>
像这样:
/** @var \ArrayIterator $iterator */
$iterator = $this->optionValues->getIterator();
$iterator->uasort(function (ProductOptionValue $a, ProductOptionValue $b) {
return $a->getOption()->getPosition() <=> $b->getOption()->getPosition();
});
return new ArrayCollection(iterator_to_array($iterator));