【问题标题】:Pagination in CakePHP using HABTM使用 HABTM 在 CakePHP 中进行分页
【发布时间】:2014-04-09 02:04:10
【问题描述】:

哇,CakePHP 真的没有解决这个问题。

经过数小时的搜索,我发现了下面的解决方案(可能会或可能不会过时),但我在应用 paginatior 'limit' => 10 或其他排序时遇到了问题。

任何想法我错过了什么?

我的模特:

public $hasAndBelongsToMany = array(
    'Post' => array(
        'className'              => 'Post',
        'joinTable'              => 'tags_posts',
        'foreignKey'             => 'tag_id',
        'associationForeignKey'  => 'post_id',  
        'order'                  => array('Post.created DESC'),
        'unique'                 => true
    )
);

在我的控制器中的 view()

public function view($id) {
    $this->Tag->bindModel(array('hasOne' => array('TagsPost')), false);     
    $this->set('tag', $this->paginate('Tag', array('TagsPost.tag_id' => $id))); 
}

在我看来,我必须改变:

foreach ($tag['Post'] as $post)

foreach ($tag[0]['Post'] as $post)

【问题讨论】:

  • 您究竟想在视图中显示什么?所有带有特定标签的帖子?另外,我假设您正在显示的是 Tags 控制器的 View 方法,对吗?请更具体。我可能会向您展示一个很好的解决方案,因为我最近遇到了相同或类似的问题。
  • 我们需要查看您的 $this->paginate 数组。您可以在对记录进行分页之前进行设置。

标签: cakephp has-and-belongs-to-many


【解决方案1】:

您的视图方法应如下所示:

public function view($id) {
      $this->Paginate['limit'] = 10;
      $this->Paginate['conditions'] = array('TagsPost.tag_id' => $id);
      $this->Tag->bindModel(array('hasOne' => array('TagsPost')), false);     
      $this->set('tag', $this->paginate('Tag')); 
}

请询问它是否不适合您。

【讨论】:

  • 好一个。但是,这再次绑定了其他模型。
【解决方案2】:

使用 CakePHP 2.x 测试

public function view ($id)
{
  $this->paginate = array (
                        'limit' => 10,
                        'conditions' => array('TagsPost.tag_id' => $id)
                    );
  $this->Tag->bindModel(array('hasOne' => array('TagsPost')), false);     
  $this->set('tag', $this->paginate('Tag')); 
}

【讨论】:

    猜你喜欢
    • 2010-11-30
    • 1970-01-01
    • 1970-01-01
    • 2013-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-27
    • 2014-07-05
    相关资源
    最近更新 更多