orderBy not affecting with Distinct

I am trying to get latest record each register group.
id | register | created
1 | 2 | date
2 | 2 | date
3 | 3 | date
4 | 1 | date
5 | 3 | date
$this->Visitors->find()->orderDesc(‘created’)->where([‘visitstatus_id’ => $status])->distinct(‘register’);

OrderBy not affecting. Distinct always selects first record.

Aggregate Functions (distinct, count) don’t care about order of the rows. Distinct use first row of the group by result.

What are you trying to get?

I want to get a latest record from each register and get all of them in single result.
For example by above data.

I don’t know your models names. I asume that table is Visitors. I tried to be as generic as possible.

// In the Table
function findLatestIdByColumn(Query $query, array $options)
    $column = $options['latest_column'];

    return $query
        ->select(['id' => $this->aliasField('id')])
        ->where(function (QueryExpression $exp, Query $query) {
            $subquery = $this->find('all');
                    'created' => $subquery->func()->max($this->aliasField('created')),

            return $exp->in(
                $query->newExpr(sprintf('(%s, %s)', $this->aliasField($column), $this->aliasField('created'))),
        ->formatResults(function (CollectionInterface $results) {
            return $results->map(function ($row) {
                return $row->id;
        ->epilog('/* findLatestIdByColumn */');

// In your controller or where you want the latest records
$ids = $this->Visitors->find('LatestIdByColumn', ['latest_column' => 'register'])->toArray();
$query = $this->Visitors->find('all')->where(['Visitors.id IN' => $ids]);

This code works for cake 3.x and 4.x
Although in 4.x it should be easier with window functions (and if you db supports them)