Sonata Admin Bundle: sort by count one to many relation

831 views Asked by At

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' => [],
            ]
        );
}
1

There are 1 answers

2
Yann Schepens On

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)