5

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.

Community
  • 1
  • 1
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153

2 Answers2

6

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

Matteo
  • 37,680
  • 11
  • 100
  • 115
3

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();
        });
        $this->subjectTags = new ArrayCollection($tags);
    }

}

Be careful with performance though, this eagerly loads the collection whatever its fetch mode.

Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
  • great trick. But what about `cascade`parameter ? I tried your solution and got an error type `update or delete on table "..." violates foreign key constraint ...`. I think it's because of the new Collection – ceadreak Jan 07 '16 at 11:31
  • Thanks for this, helped with a complex one-to-many sort – Alexei Tenitski Feb 15 '23 at 06:58