yii2实现分页功能

2021-12-23 15:13:42 浏览数 (1)

sql:

代码语言:javascript复制
CREATE TABLE `country` (
  `code` CHAR(2) NOT NULL PRIMARY KEY,
  `name` CHAR(52) NOT NULL,
  `population` INT(11) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `country` VALUES ('AU','Australia',18886000);
INSERT INTO `country` VALUES ('BR','Brazil',170115000);
INSERT INTO `country` VALUES ('CA','Canada',1147000);
INSERT INTO `country` VALUES ('CN','China',1277558000);
INSERT INTO `country` VALUES ('DE','Germany',82164700);
INSERT INTO `country` VALUES ('FR','France',59225700);
INSERT INTO `country` VALUES ('GB','United Kingdom',59623400);
INSERT INTO `country` VALUES ('IN','India',1013662000);
INSERT INTO `country` VALUES ('RU','Russia',146934000);
INSERT INTO `country` VALUES ('US','United States',278357000);

控制器:

第一:一页5个。 总数:$query->count();

代码语言:javascript复制
<?php
namespace frontendcontrollers;
use Yii;
use commonmodelsCountry;
use yiidataPagination;
use yiiwebController;
class CygController extends Controller
{
	 public function actionIndex()
    {
          $query=Country::find();
          $pagination=new Pagination([
            'defaultPageSize'=>5,
            'totalCount'=>$query->count(),
            ]);
          $countries=$query->orderBy('name')->offset($pagination->offset)->limit([$pagination->limit])->all();
           return $this->render('index', [
            'countries' => $countries,
            'pagination' => $pagination,
        ]);
    } 
    
}

model:

代码语言:javascript复制
<?php

namespace commonmodels;

use yiidbActiveRecord;

class Country extends ActiveRecord
{
	
}

视图:

代码语言:javascript复制
<?php
use yiihelpersHtml;
use yiiwidgetsLinkPager;
?>
<h1>Countries</h1>
<ul>
<?php foreach ($countries as $country): ?>
    <li>
        <?= Html::encode("{$country->name} ({$country->code})") ?>:
        <?= $country->population ?>
    </li>
<?php endforeach; ?>
</ul>

<?= LinkPager::widget(['pagination' => $pagination]) ?>

效果:

0 人点赞