简体   繁体   中英

Sonata Admin Bundle: sort by count one to many relation

How to add sort by number of votes in admin?

I have a nominee entity with relation One To Many vote. I need to allow to sort by number of votes for nominees.

I try a solution from here:https://github.com/sonata-project/SonataAdminBundle/issues/1077 and first here: Sonata Admin Bundle: show total count of collection on list view

But I get error message: [Semantical Error] line 0, col 184 near 'v_id_count ASC,': Error: 'v_id_count' is not defined.

Here's the code from NomineeAdmin:

public function createQuery($context = 'list')
{
    $query = parent::createQuery($context);

    if ('list' === $context) {
        $parameters = $this->getFilterParameters();

        if ('getVotesCount' === $parameters['_sort_by']) {
            $rootAlias = $query->getRootAliases()[0];

            $query
                ->addSelect('COUNT(v.id) as v_id_count')
                ->leftJoin($rootAlias . '. votes', 'v')
                ->groupBy($rootAlias . '.id')
                ->orderBy('v_id_count', $parameters['_sort_order']);

        }
    }

    return $query;
}

protected function configureListFields(ListMapper $listMapper)
{
    $listMapper
        //...
        ->add(
            'getVotesCount',
            null,
            [
                'sortable'                         => true,
                'sort_field_mapping'               => ['fieldName' => 'id'],
                'sort_parent_association_mappings' => [],
            ]
        );
}

Have you tried to add a getter method within your entity to return the number of relation and used it as sort_field_mapping ?

getVotesNumber(): int { ... }

...

'sort_field_mapping' => ['fieldName' => 'votesNumber'],

I have not tried, but it should work (and this way, you won't have to make sql request)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM