odan / slim4-skeleton

A Slim 4 Skeleton
https://odan.github.io/slim4-skeleton/
MIT License
439 stars 80 forks source link

DataTableRepository fails on DISTINCT #46

Closed cirolaferrara closed 3 years ago

cirolaferrara commented 3 years ago

If $query contains DISTINCT clause, recordsTotal and recordsFiltered displays wrong value.

odan commented 3 years ago

What have you tried so far?

cirolaferrara commented 3 years ago

Hi @odan. This is the database dump This is the method into Repository This is the result This is what I think must have

odan commented 3 years ago

Ok this is a special use case. DISTINCT is implemented by GROUP BY under the hood.

The SQL of your query looks like this:

SELECT `people`.* FROM `people_link`
LEFT JOIN `people` `people` ON people_link.id_people = people.id
GROUP BY `people`.`id`

So this query would give the same result:

$query = $this->queryFactory->newSelect('people_link');
$query->select(['people.*'])
    ->group('people.id')
    ->leftJoin('people', 'people_link.id_people = people.id');

Your requirement is to get count of number of groups. So we need two operations-

To fix the counter you have to open the class DataTableRepository and then replace this line:

$countQuery = clone $query;

with this line:

$countQuery = $this->queryFactory->newQuery()->from(['sub' => $query]);

Resulting SQL for the count query:

SELECT (COUNT(*)) AS `count` FROM (SELECT `people`.* 
FROM `people_link` 
LEFT JOIN `people` `people` ON people_link.id_people = people.id 
GROUP BY `people`.`id` ) `sub`

This fix should give you the correct count value:

image

cirolaferrara commented 3 years ago

Perfect! Thank you 👍