在find方法中使用groupby的Cakephp
我正在尝试对我的关系数据库使用Group by in find方法。我想从由user_id筛选的结果集中获取具有唯一receiver_id的最新记录,下面是我的代码:在find方法中使用groupby的Cakephp,php,mysql,cakephp,Php,Mysql,Cakephp,我正在尝试对我的关系数据库使用Group by in find方法。我想从由user_id筛选的结果集中获取具有唯一receiver_id的最新记录,下面是我的代码: $this->loadModel('Chat'); $lastChat = $this->Chat->find('all', array( 'conditions' => array( 'Chat.user_id' => $use
$this->loadModel('Chat');
$lastChat = $this->Chat->find('all', array(
'conditions' => array(
'Chat.user_id' => $user_id['User']['id']
),
'fields' => array(
'Chat.id',
'Chat.chat',
'Chat.user_id',
'Chat.receiver_id',
'Chat.read',
'Chat.created'
),
'group' => array('Chat.receiver_id'),
'order' => array('Chat.created DESC')
));
然而,这似乎不起作用。我不知道为什么,但我只得到一个结果
如何使用基于以上的规则获得多个结果。请尝试以下操作:
$db = $this->Chat->getDataSource();
$chats = $db->query("SELECT * , (Chat.user_id + Chat.receiver_id) AS dist
FROM (
SELECT *
FROM chats t
WHERE ( t.user_id =$id OR t.receiver_id =$id )
ORDER BY t.id DESC
) Chat
GROUP BY dist
ORDER BY Chat.id DESC");
我觉得不错。我建议您尝试找出$user\u id是否真的包含了您认为应该包含的内容。是否打印了它生成的查询?也许看看sql,你会发现你的错误。要做到这一点,只需更改getQuery的find并打印lastchat。尝试使用一个
select*from Chats,其中user_id=$userid
,看看它是否能提供更多的结果。就像api55所说的,向我们展示它生成的查询,这样会更容易帮助您。