Cakephp以升序显示最新的4个结果

时间:2014-02-07 05:08:53

标签: cakephp-2.3

我试图按升序显示最新的4个结果。请帮我实现这个目标。

示例:

result3
result4
result5
result6

当我尝试以下代码时,我得到以下结果,但我希望最后4个结果按升序排列。

$results=$this->Comment->find('all',array('conditions'=>array('feed_id'=>
$feedid,'status'=>'A'),
'recursive' => 1,'order' => 'Comment.id ASC','limit'=>4, 'offset'=>0));

RESULT1
RESULT2
result3
result4

以下查询将有效,但我想写一个cakephp find

SELECT * 
FROM (SELECT *
FROM `comments` WHERE `feed_id`=46 ORDER BY created DESC LIMIT 0 , 4) t
ORDER BY id ASC

2 个答案:

答案 0 :(得分:0)

如果我很好理解你的问题,这是一个解决方案。

MySQL的

SELECT 
    * 
FROM 
    `comments` AS c
WHERE 
    c.feed_id = 46
ORDER BY 
    c.created DESC, 
    c.id ASC 
LIMIT 4

cakephp的

$conditions = array(
    'feed_id'=>46,
    'status'=>'A'
);
$order = array(
    'Comment.created DESC,
    'Comment.id ASC
);
$limit = 4;
$recursive = 1;

# fetch results
$results = $this->Comment->find('all', 
   array(
       'conditions' => $conditions, 
       'recursive' => $recursive, 
       'order' => $order, 
       'limit' => $limit
   )
);

答案 1 :(得分:0)

我意识到这可能不是一个“纯粹”的解决方案,但是如果您需要显示的行数似乎已知且有限,我建议您执行以下操作:

// fetch results
$results = $this->Comment->find('all', 
   array(
       'conditions' => array(
            'feed_id'=>46,
            'status'=>'A'
       ), 
       'recursive' => 1,
       'order' => array(
            'Comment.created DESC',
            'Comment.id DESC'
        ),
       'limit' => 4
   )
);
// Sort them as you need
$results = Hash::sort($results, '{n}.Comment.created', 'asc');

排序可以在模型,控制器或视图中完成,但我建议后者,因为你看起来更像是一个显示要求而不是我在模型中放置的东西。 我没有足够的MVC“纯度”来肯定地说。

相关问题