Sort a doctrine's @OneToMany ArrayCollection

后端 未结 2 1646
轻奢々
轻奢々 2021-01-13 11:54

My question is close to this one, but does not exactly fit with mine.

I\'ve this column in an entity:

/**
 * @var ArrayCollection[SubjectTag]
 *
 * @         


        
相关标签:
2条回答
  • 2021-01-13 12:18

    Try using the doctrine2 ORM functionality for Ordering To-Many Associations like this:

    /**
     * @var ArrayCollection[SubjectTag]
     *
     * @ORM\OneToMany(targetEntity="SubjectTag", mappedBy="subject")
     * @ORM\OrderBy({"position" = "ASC"})
     * @Assert\Count(max = 10, maxMessage = "You can't create more than 10 tags.")
     * @Assert\Valid()
     */
    protected $subjectTags;
    

    Hope this help

    0 讨论(0)
  • 2021-01-13 12:40

    I found a solution, using @HasLifeCycleCallbacks.

    use Doctrine\ORM\Mapping as ORM;
    
    /**
     * ...
     * @ORM\HasLifecycleCallbacks
     */
    class Subject
    {
    
        /**
         * @var ArrayCollection[SubjectTag]
         *
         * @ORM\OneToMany(targetEntity="SubjectTag", mappedBy="subject")
         * @Assert\Count(max = 10, maxMessage = "You can't create more than 10 tags.")
         * @Assert\Valid()
         */
        protected $subjectTags;
    
    
        /**
         * @ORM\PostLoad
         */
        public function onPostLoad()
        {
            $tags = $this->subjectTags->toArray();
            usort($tags, function($a, $b)
            {
                return $a->getPosition() == $b->getPosition() ? 0 : ($a->getPosition() > $b->getPosition() : -1 : 1);
            });
            $this->subjectTags = new ArrayCollection($tags);
        }
    
    }
    
    0 讨论(0)
提交回复
热议问题