I'm developing a social application with cakephp 3.
I'm working on the messanging function right now. It works this way, that on the left side one gets displayed the users, who one has conversations with and in the middle is the conversation.
I want the users to be sorted by last messaging date. Meaning, if Peter was the last one I wrote to, then Peter should appear on top and so on.
I have the following query:
$query = $this->Messages
->find('all', [
'fields' => [
'MAX(`messages`.`max_date`)',
'id',
'sender_id',
'reciever_id',
]
])
->where([
'sender_id = ' => $active_user_id
])
->orWhere([
'reciever_id = ' => $active_user_id
])
->group([
'sender_id',
'reciever_id'
])
->order([
'id' => 'DESC'
]);
For performance reasons I added a grouping by sender_id and reciever_id, since I don't want to recieve all messages, but only find the users, that I wrote with so far.
The problem is that the group-statement destroys the sorting. So I thought about a max-aggregate-function to preserve the order.
However I get the following error-message by the cakephp framework:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'MAX(`messages`__`max_date`), Messages.id AS `Messages__id`, Messages.sender_id A' at line 1
So does anyone know, what is wrong with my query? I gave my best to follow the example in the documentation.
Why does it say messages
__max_date
and not messages
.max_date
?