Group by ID and Order by date

2019-03-04 04:26发布

问题:

$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'))
        );