【问题标题】:Sort a doctrine's @OneToMany ArrayCollection对学说的@OneToMany ArrayCollection 进行排序
【发布时间】:2014-12-14 12:20:26
【问题描述】:

我的问题接近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 中定义的位置动态排序我的标签。

【问题讨论】:

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


    【解决方案1】:

    尝试像这样对Ordering To-Many Associations 使用教义2 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;
    

    希望有帮助

    【讨论】:

    • 太漂亮了!
    【解决方案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);
        }
    
    }
    

    【讨论】:

    • 绝招。但是cascadeparameter 呢?我尝试了您的解决方案并收到错误类型update or delete on table "..." violates foreign key constraint ...。我想是因为新的 Collection
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    • 2016-01-13
    • 2012-03-14
    • 2014-05-08
    • 1970-01-01
    • 2014-08-13
    • 1970-01-01
    相关资源
    最近更新 更多