如何获取CakePHP 3中通过分页检索的记录总数?

时间:2018-12-21 04:06:35

标签: php cakephp cakephp-3.0

我在CakePHP 3中有一个问题,无法正确进行分页。

如何获取CakePHP 3中通过分页检索的记录总数?

1 个答案:

答案 0 :(得分:0)

这可能会对您有所帮助。 在您的控制器中,即 UsersController.php 进行分页,如下所示:

public function index()
{

    //set your pagination limit 10
    $this->paginate = [
        'limit' => 10
    ];

   //query all users
   $users = $this->paginate($this->Users->find('all'));

    //pass to template
    $this->set(compact('users'));

}

在您的模板视图中,即 users / index.ctp 放置此代码以显示您的分页

<div class="users index large-9 medium-8 columns content">
<h3><?= __('Users') ?></h3>
<table cellpadding="0" cellspacing="0" border="1">
    <thead>
    <tr>
        <th scope="col"><?= $this->Paginator->sort('id') ?></th>
        <th scope="col"><?= $this->Paginator->sort('fullname') ?></th>
        <th scope="col"><?= $this->Paginator->sort('email') ?></th>
        <th scope="col"><?= $this->Paginator->sort('handphone') ?></th>
        <th scope="col" class="actions"><?= __('Actions') ?></th>
    </tr>
    </thead>
    <tbody>
    <?php foreach ($users as $user): ?>
        <tr>
            <td><?= $this->Number->format($user->uid) ?></td>
            <td><?= h($user->fullname) ?></td>
            <td><?= h($user->email) ?></td>
            <td><?= h($user->handphone) ?></td>
            <td class="actions">
                <?= $this->Html->link(__('View'), ['action' => 'view', $user->id]) ?>
                <?= $this->Html->link(__('Edit'), ['action' => 'edit', $user->id]) ?>   
            </td>
        </tr>
    <?php endforeach; ?>
    </tbody>
</table>
<div class="paginator">
    <ul class="pagination">
        <?= $this->Paginator->first('<< ' . __('first')) ?>
        <?= $this->Paginator->prev('< ' . __('previous')) ?>
        <?= $this->Paginator->numbers() ?>
        <?= $this->Paginator->next(__('next') . ' >') ?>
        <?= $this->Paginator->last(__('last') . ' >>') ?>
    </ul>
    <p><?= $this->Paginator->counter(['format' => __('Page {{page}} of {{pages}}, showing {{current}} record(s) out of {{count}} total')]) ?></p>
</div>

相应地在变量上方进行更改,以匹配您的表实体(列名)。

  

提示:如果使用CakePHP bake命令,您将获得所有这些   默认情况下分页