Sort a doctrine's @OneToMany ArrayCollection

穿精又带淫゛_ 提交于 2019-12-01 03:34:11

问题


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

I've this column in an entity:

/**
 * @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;

I want to dynamically order my tags by a position, defined in SubjectTag.position.


回答1:


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




回答2:


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);
    }

}


来源:https://stackoverflow.com/questions/27469222/sort-a-doctrines-onetomany-arraycollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!