如何在symfony2中对实体的arrayCollection进行排序

问题描述 投票:29回答:4

我有一个具有此属性的实体“容器”

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

该属性是一个数组集合......

public function __construct() {
    $this->content = new \Doctrine\Common\Collections\ArrayCollection();
}

......用这两种标准方法

/**
 * Add content
 *
 * @param BizTV\ContentManagementBundle\Entity\Content $content
 */
public function addContent(\BizTV\ContentManagementBundle\Entity\Content $content)
{
    $this->content[] = $content;
}

/**
 * Get content
 *
 * @return Doctrine\Common\Collections\Collection 
 */
public function getContent()
{
    return $this->content;
}

现在我的问题是,是否有一种平滑的方法可以在getContent()调用中构建排序功能?我不是php wiz,当然也没有在symfony2中经验丰富,但我随便学习。

内容实体本身有一个像这样的排序INT,我想对它进行排序:

/**
 * @var integer $sortOrder
 *
 * @ORM\Column(name="sort_order", type="integer")
 */
private $sortOrder; 
sorting symfony doctrine entities
4个回答
63
投票

您应该能够使用@ORM\OrderBy语句,该语句允许您指定列以对集合进行排序:

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

事实上,这可能是How to OrderBy on OneToMany/ManyToOne的副本

Edit

检查实现建议,您似乎必须使用连接查询获取表到集合,以便@ORM \ OrderBy注释工作:http://www.krueckeberg.org/notes/d2.html

这意味着您必须在存储库中编写一个方法,以返回包含连接的内容表的容器。


19
投票

如果您想确保始终根据当前属性值获得订单中的关系,您可以执行以下操作:

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

例如,如果您更改了Order属性,请使用它。适用于“最后修改日期”。


13
投票

你可以写

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

用于多个标准订购。


1
投票

您还可以通过ArrayCollection属性CriteriaorderBy进行排序,如下所示:

<?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();
        }
    }
?>
© www.soinside.com 2019 - 2024. All rights reserved.