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

Mat*_*der 31 sorting entities doctrine symfony

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

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

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

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

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

/**
 * 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;
}
Run Code Online (Sandbox Code Playgroud)

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

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

/**
 * @var integer $sortOrder
 *
 * @ORM\Column(name="sort_order", type="integer")
 */
private $sortOrder; 
Run Code Online (Sandbox Code Playgroud)

Luk*_*uke 65

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

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

实际上,这可能是如何在OneToMany/ManyToOne上订购的副本

编辑

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

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


Wou*_*iet 20

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

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

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


小智 13

你可以写

@ORM\OrderBy({"date" = "ASC", "time" = "ASC"})
Run Code Online (Sandbox Code Playgroud)

用于多个标准订购.