Ah I see. That is a little bit trickier.
in MessagesTable.php you would need to select the latest messages of each chats. Here is a MySQL 5.7 compatible sample.
public function findLatest(Query $query, array $options)
'latest' => $query->getConnection()->newQuery()
'chat_id' => 'Chats.id',
'latest' => $query->func()->max('Messages.created')
->from(['Messages' => 'messages'])
$this->getAlias() . '.chat_id' => new IdentifierExpression('latest.chat_id'),
$this->getAlias() . '.created' => new IdentifierExpression('latest.latest')
After this you need to join this into a chat query in ChatsTable.php
public function findCurrent(Query $query, array $options)
return $query->select(['Chats.id', 'Messages.created', 'Messages.message'])
['LatestMessage' => $this->Messages->find('latest', $options)],
['Chats.id = LatestMessage.Messages__chat_id']
Perhaps this is for you to help you start to think about it. There is a good chance that you should tweak a little on both queries.