Cakephp:按发布日期按外键ID和顺序分组

时间:2014-01-13 17:20:36

标签: sql cakephp

public function index() {
    $this->paginate = array(
        'order'=>array('published_date'=>'desc'),
        'group'=>'book_id',
        'conditions'=>array('Chapter.published'=>1,'Chapter.published_date <= NOW()')
    );
    $chapters = $this->paginate();
    $this->set('chapters',$chapters);

}

我的数据库有表 Book 。每本书都有很多章节

有字段'* book_id *',即外键引用表 Book 主键(id)。

这是我的索引页面。我们的想法是按照发布日期从每本书和订单中获取最新章节。在控制器 ChapterController 中,我使用 group by 语句但它没有得到最新章节,它从每本书的第一章开始。

所以,请帮我修理一下。非常感谢

1 个答案:

答案 0 :(得分:0)

我相信group by将使用结果中自然存在的第一行,并且我认为在应用group by之前,有一种简单的方法可以对结果进行排序。但我认为以下查询将为您提供所需的结果:

SELECT * FROM books INNER JOIN (SELECT * FROM chapters WHERE chapters.published = 1 AND chapters.published_date <= NOW() ORDER BY chapters.published_date DESC) AS Chapter ON Chapter.book_id = books.id GROUP BY books.id

我认为以下是CakePHP应该如何看待(我假设你正在分页书):

$this->Book->recursive = -1;  //Join manually instead
$this->paginate = array(
     'order' => array('published_date' => 'desc'),
     'group'  => 'Book.id',
     'joins' => array(
           array(
               'table' => '(SELECT * FROM chapters)',
               'alias' => 'Chapter',
               'conditions' => array(
                      'Chapter.book_id = Book.id',
                      'Chapter.published' => 1,
                      'Chapter.published_date <= NOW()',
               ),
               'type' => 'inner',
               'order' => array('published_date' => 'desc'),
           ),
      ),
 );