Kreyu / data-table-bundle

Streamlines creation process of the data tables in Symfony applications. NOT PRODUCTION READY.
https://data-table-bundle.swroblewski.pl
MIT License
75 stars 14 forks source link

Make Doctrine ORM filters compatible with aggregate functions #116

Closed Kreyu closed 3 months ago

Kreyu commented 3 months ago

Currently, if we add a filter with aggregate function in query path (e.g. a simple COUNT or SUM), the exception comes in:

An exception occurred while executing a query: SQLSTATE[42803]: Grouping error: 7 ERROR: aggregate functions are not allowed in WHERE

This is because with aggregate functions, we have to add HAVING clause instead of a WHERE, and currently there's no way to configure the Doctrine ORM filters to do that.

Temporarily, as a workaround, use the CallbackFilterType:

->addFilter('foo', CallbackFilterType::class, [
    'callback' => function (DoctrineOrmProxyQuery $query, FilterData $data) {
        // note: using getUniqueParameterId is completely optional
        $parameterName = 'foo'.$query->getUniqueParameterId();

        $query
            ->andHaving("COUNT(foo.bar) = :$parameterName")
            ->setParameter($parameterName, $data->getValue())
        ;
    },
])
Kreyu commented 3 months ago

The Doctrine paginator does not support queries with HAVING clause. As a workaround, use a subquery.