对教条的@OneToMany ArrayCollection进行排序

时间:2014-12-14 12:20:26

标签: php symfony doctrine-orm one-to-many

我的问题接近this one,但并不完全适合我的。

我在一个实体中使用此列:

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

我想按照SubjectTag.position中定义的位置动态订购我的代码。

2 个答案:

答案 0 :(得分:5)

尝试使用Ordering To-Many Associations的doctrine2 ORM功能,如下所示:

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

希望这个帮助

答案 1 :(得分:2)

我找到了一个解决方案,使用@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);
    }

}