I Like to sort the query into DESC then after sort it to ASC using ID

Which means the 50 results I want to sort it to DESC then to ASC

$data = $this->Messages->find(‘all’)
->where([
‘messages.channel_id =’ => $channelId
])
->order([‘messages.created’ => ‘DESC’, ‘messages.id’ => ‘ASC’],true)
->limit(50);
return $this->response->withType(‘application/json’)
->withStringBody(json_encode($data));

I think all your references to messages should be Messages instead?

yeah, But the order didt’n follow the ASC order. I want the id of 36 should start at the top

You’ve asked it to sort first by descending order of created timestamp, and then by id. The id sort will be used only if it finds two with the same creation time.

1 Like

Oh, you want the most recent 50, but sorted by increasing id? What you have will clearly not do that. Might have to do something like

$data = $this->Messages->find(‘all’)
    ->where(['Messages.channel_id' => $channelId])
    ->order(['Messages.created' => 'DESC'])
    ->limit(50)
    ->sortBy('id', SORT_ASC, SORT_STRING)
    ->toArray();
1 Like

Thanks Zuluru but I also tried the sortBy but It didn’t work