简体   繁体   中英

Symfony 4 Sorting Filtered Array Collection

I am having trouble sorting a collection resulting from a one-to-many relationship that has been filtered. I have a quiz that has questions:

class Quiz
{
/**
 * One quiz has many questions. This is the inverse side.
 * @ORM\OneToMany(targetEntity="Question", mappedBy="assessment")
 * @ORM\OrderBy({"num" = "ASC"})
 */
 private $questions;

 public function __construct() {
    $this->questions = new ArrayCollection();
 }

This works as expected. However, when I modify the getter to exclude inactive (soft-deleted) questions, the sort order is lost.

public function getQuestions()
{
    // filter to never return soft deleted questions
    $criteria = Criteria::create()->where(Criteria::expr()->eq("active", true));
    return $this->questions->matching($criteria);
}

In fact, with this getter in place, if I modify the order by clause to a nonexistent column, I do not get an unrecognized field exception as I would expect:

@ORM\OrderBy({"nonexistantcolumn" = "ASC"}) 

This leads me to believe that somehow the criteria filtering is overriding the annotation. Any ideas on how to resolve this would be much appreciated.

Besides filtering, Criteria can also sort a collection:

public function getQuestions()
{
    // filter to never return soft deleted questions
    $criteria = Criteria::create()
        ->where(Criteria::expr()->eq("active", true))
        ->orderBy(["num" => Criteria::ASC]);
    return $this->questions->matching($criteria);
}

However, consider adding another unfiltered getter since this will prevent you from actually deleting inactive elements, or moving this logic to a repository method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM