奏鸣曲管理员-“按...排序”相关表中的字段 [英] Sonata admin - "order by" field in related table

查看:85
本文介绍了奏鸣曲管理员-“按...排序”相关表中的字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个产品管理员班。产品实体与类别实体具有多对一关系,即产品与类别相关联。

I have a Product admin class. The Product entity has a many-to-one relationship with a Category entity, i.e. a product is associated with a category.

在产品的管理列表页面中,我需要按每种产品所关联的类别名称(按字母顺序)进行排序。

In the admin "list" page for products, I need to sort by the category name (alphabetically) that each product is associated with.

如果字段位于实体本身上,则设置默认字段进行排序很容易(有关操作方法,请参见 Sonata管理员捆绑包订单)。但是我无法弄清楚如何按相关表中的字段排序。

Setting the default field to sort by is easy if the field is on the entity itself (see Sonata admin bundle order for how to do this). But I cannot figure out how to sort by a field in a related table.

我们将不胜感激。

推荐答案

这似乎是一种解决方法,但它可以工作。您必须添加一个连接重写createQuery()方法,然后分配一个默认sortBy来覆盖$ datagridValues:

It seems a workaround, but it works. You have to add a join overriding createQuery() method, than assign a default sortBy overriding $datagridValues:

<?php
use Sonata\DoctrineORMAdminBundle\Datagrid\ProxyQuery;

class ExpenseAdmin extends Admin
{
    protected $datagridValues = array(
        '_page'       => 1,
        '_sort_order' => 'ASC', // sort direction
        '_sort_by' => 'c.name' // field name
    );

    /**
     * @return \Sonata\AdminBundle\Datagrid\ProxyQueryInterface
     */
    public function createQuery($context = 'list')
    {
        $query = parent::createQuery($context);

        return new ProxyQuery($query
            ->join(sprintf('%s.category', $query->getRootAlias()), 'c'));
    }
}

这篇关于奏鸣曲管理员-“按...排序”相关表中的字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆