I'm looking for the way to avoid duplicates in a query in Cakephp5.
Here is my table rubriques :
id | ... | model | ...
======================
1 | ... | CustomRubriques | ...
2 | ... | CustomRubriques | ...
3 | ... | CustomRubriques | ...
4 | ... | CustomRubriques | ...
Here is my query :
$rubriquesModels = $this->Rubriques
->find()
->select('model')
->distinct()
->all()
->extract('model');
debug($rubriquesModels->toArray());
Here is the result of the query :
(int) 0 => 'CustomRubriques',
(int) 1 => 'CustomRubriques',
(int) 2 => 'CustomRubriques',
(int) 3 => 'CustomRubriques',
Why doesn't distinct() remove the duplicates ?
--EDIT--
It seems the problem comes from my RubriquesTable where I do :
// in RubriquesTable.php
public function beforeFind(Event $event, SelectQuery $query, ArrayObject $options, $primary)
{
$query
->enableAutoFields()
->find('translations');
return $query;
}
When I remove this callback, my query with “distinct” works well.
Don't know why does the code of my callback beforeFind() make my query ->distinct() not working... (?)
distinct()are optional, but I've always used it like->distinct('model').->distinct('model')...GROUP BYinstead ofDISTINCTto implement this, and it's doing it in a way that wants theidto be in the selected fields. You might try->select(['id', 'model'])to see if that resolves it; you're throwing away everything else with theextractcall anyway, andidis a very small extra bit of data to pull across.