Group by ID and Order by date

会有一股神秘感。 提交于 2019-12-20 06:32:58

问题


$lastComments = $this->Comment->find('all', array('fields' => array('Comment.news_id', 'Comment.date', 'Comment.content'),
                'group' => array('Comment.news_id, Comment.date'),    
                'order' => array('Comment.date DESC'))
        );

The idea is to get latest comment from unique topics (1 comment - 1 topic).

This code doesn't handle unique ID's (unique topics), how Can I fix that?

Distinct doesn't work.

$lastComments = $this->Comment->find('all', array('fields' => array('Comment.news_id', 'Comment.date', 'Comment.content'),
                'group' => array('Comment.news_id'),    
                'order' => array('Comment.date DESC'))
        );

This code will return unique topics but order by date doesn't work :/


回答1:


I think this will be help you a bit...Just try this

$this->Post->find('all',array( 'order' => array('id DESC') )  ); 



回答2:


$this->Comment->find('first', array('order'=>array('Comment.id DESC')));



回答3:


You mentioned DISTINCT didn't work. Did you have trouble using the DISTINCT syntax in CakePHP, or did using DISTINCT correctly not yield the correct results? I'd try:

$lastComments = $this->Comment->find('all', array('fields' => 
                                                    array('DISTINCT Comment.news_id', 'Comment.date', 'Comment.content'),
                                                 'order' => array('Comment.date DESC'))
    );



回答4:


If it can help, I had the same problem without cakephp, the solution was to use a max(date)

Prehaps something like that in cakephp :

$lastComments = $this->Comment->find('all', 
array('fields' => array('Comment.news_id', 
                        'Comment.date', 
                        'Comment.content'),
                'group' => array('Comment.news_id'),    
                'order' => array('max(Comment.date) DESC'))
        );


来源:https://stackoverflow.com/questions/6858408/group-by-id-and-order-by-date

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