독트린\공통\수집\"을 "usort"합니다.배열 모음?
다양한 경우에 나는 분류할 필요가 있습니다.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 배열로 복사하고 다시 복사해야 할 때는 이것이 최선의 방법이 아니라고 생각합니다.나는 a를 "사용"하는 더 나은 방법이 있는지 궁금합니다.Doctrine\Common\Collections\ArrayCollection
제가 놓친 의사가 있나요?
기존 컬렉션을 정렬하려면 ArrayCollection::getIterator() 메서드를 찾으며 ArrayCollection을 반환합니다.예:
$iterator = $collection->getIterator();
$iterator->uasort(function ($a, $b) {
return ($a->getPropery() < $b->getProperty()) ? -1 : 1;
});
$collection = new ArrayCollection(iterator_to_array($iterator));
가장 쉬운 방법은 리포지토리의 쿼리가 정렬을 처리하도록 하는 것입니다.
범주 도면요소와 다대다 관계가 있는 수퍼 도면요소가 있다고 가정합니다.
그런 다음 다음과 같은 리포지토리 방법을 만듭니다.
// 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()
;
}
정렬을 매우 쉽게 합니다.
Dutrin 2.3 이후 Criteria API를 사용할 수 있습니다.
예:
<?php
public function getSortedComments()
{
$criteria = Criteria::create()
->orderBy(array("created_at" => Criteria::ASC));
return $this->comments->matching($criteria);
}
참고: 이 솔루션을 사용하려면 다음에 대한 일반 액세스 권한이 필요합니다.
$createdAt
재산 또는 공공 이득 방법getCreatedAt()
.
배열 컬렉션 필드가 있는 경우 주석과 함께 정렬할 수 있습니다.예:
Society라는 이름의 엔티티가 많은 라이센스를 가지고 있다고 가정합니다.사용할 수 있습니다.
/**
* @ORM\OneToMany(targetEntity="License", mappedBy="society")
* @ORM\OrderBy({"endDate" = "DESC"})
**/
private $licenses;
그러면 ArrayCollection by endDate(날짜 필드)가 desc순으로 정렬됩니다.
Dutrin 문서 참조: http://docs.doctrine-project.org/projects/doctrine-orm/en/latest/reference/annotations-reference.html#orderby
독트린 기준은 관련 개체에 대한 속성별 순서를 지정할 수 없습니다.
만약 당신이 그것을 하고 싶다면, 당신은 (나처럼) 사용해야 합니다.uasort
이전 응답과 같은 반복기의 방법과 PHP 7을 사용하면 우주선 운영자를 사용할 수 있습니다.<=>
이런 식으로:
/** @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));
마지막 Symfony 5.3에서 @ 주석이 없는 경우 필요합니다.
...
#[OrderBy(['sortOrder' => 'ASC'])]
private Collection $collection;
#[Column(type: 'integer')]
private int $sortOrder = 0;
...
당신의 실체에.
모든 값을 가져와서 이 값을 정렬한 다음 정렬된 값으로 속성을 덮어쓰는 것은 어떻습니까?
public function sortMyDateProperty(): void
{
$values = $this->myAwesomeCollection->getValues();
usort($values, static function (MyAwesomeInterface $a, MyAwesomeInterface $b): int {
if ($a->getMyDateProperty()->getTimestamp() === $b->getMyDateProperty()->getTimestamp()) {
return 0;
}
return $a->getMyDateProperty() > $b->getMyDateProperty() ? 1 : -1;
});
$this->myAwesomeCollection = new ArrayCollection($values);
}
언급URL : https://stackoverflow.com/questions/16705425/usort-a-doctrine-common-collections-arraycollection
'prosource' 카테고리의 다른 글
Swift 4.0으로 컴파일된 모듈은 Swift 4.0.1에서 가져올 수 없습니다. (0) | 2023.08.06 |
---|---|
유형 범주별 SQL 총합 (0) | 2023.08.06 |
Spring Boot REST 응용 프로그램에서 gzip 요청 처리 (0) | 2023.08.01 |
Visual Studio 2008에서 IntelliSense가 안정적으로 작동하도록 하는 방법 (0) | 2023.08.01 |
"@WebMvcTest"에 빈 하나 추가 (0) | 2023.08.01 |