0

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... (?)

5
  • The parameters to distinct() are optional, but I've always used it like ->distinct('model'). Commented Oct 2, 2024 at 13:54
  • @GregSchmidt it returns a "Database Error" when I do ->distinct('model')... Commented Oct 2, 2024 at 14:03
  • Surely there are more specifics about that error than just "Database Error"? Commented Oct 2, 2024 at 16:08
  • @GregSchmidt SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #2 of SELECT list is not in GROUP BY clause and contains nonaggregated column 'cms-infoliv5.Rubriques.id' which is not functionally dependent on columns in GROUP BY clause; this is incompatible with sql_mode=only_full_group_by Commented Oct 2, 2024 at 17:08
  • Seems Cake is using GROUP BY instead of DISTINCT to implement this, and it's doing it in a way that wants the id to be in the selected fields. You might try ->select(['id', 'model']) to see if that resolves it; you're throwing away everything else with the extract call anyway, and id is a very small extra bit of data to pull across. Commented Oct 2, 2024 at 20:11

1 Answer 1

0

change ->distinct() to ->distinct(['Rubriques.model'])

Sign up to request clarification or add additional context in comments.

2 Comments

thanks but the problem is not coming from here. I've edited my question.
maybe it will left join to i18n table too.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.