how to sort an entity's arrayCollection in symfony2

丶灬走出姿态 提交于 2019-12-02 20:07:07
Luke

You should be able to use the @ORM\OrderBy statement which allows you to specify columns to order collections on:

/**
 * @ORM\OneToMany(targetEntity="BizTV\ContentManagementBundle\Entity\Content", mappedBy="container")
 * @ORM\OrderBy({"sort_order" = "ASC"})
 */
private $content;

In fact this may be a duplicate of How to OrderBy on OneToMany/ManyToOne

Edit

Checking for implementation advice it appears that you must fetch the tables with a join query to the collection in order for the @ORM\OrderBy annotation to work: http://www.krueckeberg.org/notes/d2.html

This means that you must write a method in the repository to return the container with the contents table joined.

Wouter Van Vliet

If you want to be sure that you always get your relations in the order based on current property values, you can do something like this:

$sort = new Criteria(null, ['Order' => Criteria::ASC]);
return $this->yourCollectionProperty->matching($sort);

Use that for example if you've changed the Order property. Works great for a "Last modified date" as well.

Yasmany Hernandez Hernandez

You can write

@ORM\OrderBy({"date" = "ASC", "time" = "ASC"})

for multiple criteria ordering.

You can also sort ArrayCollection by Criteria property orderBy like so:

<?php
    namespace App/Service;

    use Doctrine\Common\Collections\ArrayCollection;
    use Doctrine\Common\Collections\Criteria;

    /**
     * Class SortService
     *
     * @package App\Service
     */
    class SortService {
        /**
         * @param SomeAbstractObject $object
         * @return SomeCollectionItem[]
         */
        public function sorted(SomeAbstractObject $object): array {
            /** $var ArrayCollection|SomeCollectionItem[] */
            $collection = $object->getCollection();

            // convert normal array to array collection object
            if(\is_array(collection)) {
                $collection = new ArrayCollection(collection);
            }

            // order collection items by position property
            $orderBy = (Criteria::create())->orderBy([
                'position' => Criteria::ASC,
            ]);

            // return sorter SomeCollectionItem array
            return $collection->matching($orderBy)->toArray();
        }
    }
?>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!