Cakephp 3同型号多重分页?

时间:2017-05-02 07:12:56

标签: cakephp controller pagination conditional-statements cakephp-3.x

我一直在研究一个项目并陷入一个问题,即一个视图需要在Cakephp 3中具有不同条件的相同模型上进行两次分页。

例如。打开和关闭同一视图上的支持票据。

以下是我的代码。有人能帮助我吗?

//Opened status pagination
$opened_paginate = [
    'contain' => ['Comments'],
    'conditions' => [
        'AND' => ['SupportTickets.status' => '1']
    ],
    'order' => ['SupportTickets.id' => 'DESC'], 
    'limit' => 1
];   

// Closed status pagination  
$closed_paginate = [
    'contain' => ['Comments'],
    'conditions' => [
        'AND' => ['SupportTickets.status' => '2']
    ],
    'order' => ['SupportTickets.id' => 'DESC'],
    'limit' => 1
];                  

$this->set('opened', $this->Paginator->paginate(
    $this->SupportTickets->find(),
    $opened_paginate
));
$this->set('closed', $this->Paginator->paginate(
    $this->SupportTickets->find(),
    $closed_paginate
)); 

2 个答案:

答案 0 :(得分:1)

您可以在一个操作中对不同的模型进行分页(请参阅docs),但我认为这不适用于同一模型。

也许你可以使用Traits或者这个来构建一些奇怪的东西,但我建议你重新考虑你想要做的事情,并且不需要在一个视图中多次分页相同的模型。

  

您可以使用单个控制器操作对多个模型进行分页   控制器的$ paginate属性和in中的scope选项   对paginate()方法的调用:

// Paginate property
public $paginate = [
    'Articles' => ['scope' => 'article'],
    'Tags' => ['scope' => 'tag']
];

// In a controller action
$articles = $this->paginate($this->Articles, ['scope' => 'article']);
$tags = $this->paginate($this->Tags, ['scope' => 'tag']);
$this->set(compact('articles', 'tags'));

答案 1 :(得分:0)

在这里我找到了答案。 https://www.ammann.info/cakephp-3-paginating-model-multiple-times-in-the-same-view/

在控制器中:

$this->loadModel('Members');
$paginator1 = $this->paginate(
    $this->Members->find()->where(['tag' => 1]), [
    'model' => 'Members',
    'scope' => 'scope1'
    ]
);

eval('namespace App\Model\Table;'
        . 'class Members2 extends \App\Model\Table\Members {}');
$this->loadModel('Members2');
$paginator2 = $this->paginate(
    $this->Members2->find()->where(['tag' => 2]), [
    'model' => 'Members2',
    'scope' => 'scope2'
    ]
);

在视图中:

// first paginator
echo $this->Paginator->sort('title', ['model' => 'Members']);
// second paginator
echo $this->Paginator->sort('title', ['model' => 'Members2']);