CakePHP find with MAX

旧城冷巷雨未停 提交于 2019-12-05 01:08:33

If I am understanding you correctly this would give you your desired result:

$messages = $this->User->Message->find('all', array(
    'conditions' => array('user_id' => $user_id), 
    'fields' => array('MAX(Node.created) AS created', '*'), 
    'group by' => 'Message.user_id',
    'order' => 'reciever_id'));

This should give you 3 results, one for each user.

Try looking at your SQL debug log by putting this in your view:

$this->Element('sql_dump');

Note that this only produces output if your debug level is not zero. I suspect that your MAX query only selects one single node with the highest value and thus doesn't return any other nodes. Ordering by created rather then selecting it with MAX would be my best bet to get this thing going.

Here's a solution under the Example using GROUP BY headline. What worked for me is in the line of:

$this->Model->find('all', array(
   'fields' => 'MAX(Model.wanthighestfield) as wanthighestfield',
   'group' => 'wantuniquefield'
));

Results in an array with the highest wanthighestfield for each wantuniquefield. I found that adding fields to the fields options is pointless as CakePHP will not fetch the fields from the same line for the array item.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!