[英]Cannot sort One-To-Many association with Doctrine
I am following the doctrine documentation about sort association: Ordering To-Many Associations 我正在遵循有关排序关联的理论文档: 订购多对多关联
I have a category entity, it has many articles: 我有一个类别实体,其中有很多文章:
class Category
{
/**
* @ORM\OneToMany(targetEntity="App\Entity\Article", mappedBy="category")
* @ORM\OrderBy({"position"="ASC"})
*/
private $articles;
}
article entity has a position field for sort: 文章实体具有一个用于排序的位置字段:
class Article
{
/**
* @Gedmo\SortablePosition
* @ORM\Column(name="position", type="integer", nullable=true)
*/
private $position;
}
and get data from controller: 并从控制器获取数据:
/**
* @Route("/zen", name="zen")
*/
public function zen(){
$category = $this->getDoctrine()->getRepository(Category::class);
$categories = $category->createQueryBuilder('c')
->innerJoin('c.articles', 'a')
->addSelect('a')
->getQuery()->getResult();
return $this->render('index/zen.html.twig', [
'categories' => $categories
]);
}
notice above, I add inner join and addSelect for avoid N+1 query problem. 注意,在上面,我添加了内部连接和addSelect以避免N + 1查询问题。
in the template: 在模板中:
{% for c in categories %}
{% for a in c.articles %}
position: {{a.position}}, id: {{a.id}}
{% endfor %}
{% endfor %}
the result should be ordered by position, like: 结果应按位置排序,例如:
position: 1, id: 2
position: 2, id: 1
position: 3, id: 3
position: 4, id: 4
but actually ordered by id: 但实际上是按ID排序的:
position: 2, id: 1
position: 1, id: 2
position: 3, id: 3
position: 4, id: 4
The Sortable
behavior, when enabled, will attach a listener to the entity to update the SortablePosition
property of all entries when one is updated, but will not affect query behavior. 启用
Sortable
行为后,它将在实体上附加一个侦听器以更新所有条目的SortablePosition
属性,但不会影响查询行为。
You have to add the ordering to the query yourself or use the repository provided by the behavior by declaring it in your class: 您必须自己在查询中添加顺序,或者通过在类中声明行为来使用行为提供的存储库:
/**
* @ORM\Entity(repositoryClass="Gedmo\Sortable\Entity\Repository\SortableRepository")
*/
class Article
{
/**
* @Gedmo\SortablePosition
* @ORM\Column(name="position", type="integer", nullable=true)
*/
private $position;
}
Then you can get a queryBuilder
with the predefined order via the repository (the entity will recieve the alias n
): 然后,您可以通过存储库获取具有预定义顺序的
queryBuilder
(实体将获得别名n
):
$categories = $category->getBySortableGroupsQueryBuilder()->innerJoin('n.articles', 'a');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.