yii2.0 数据分页显示

    xiaoxiao2023-02-01  15

    第一步配置数据库文件 在application/config文件下db.php

    <?php return [ 'class' => 'yii\db\Connection', 'dsn' => 'mysql:host=localhost;dbname=yii2basic', 'username' => 'root', 'password' => 'admin', 'charset' => 'utf8', ]; 第二步:创建model文件 在application\models目录文件下 <?php namespace app\models; use yii\db\ActiveRecord; class Country extends ActiveRecord { //yii能根据类名去猜测数据表;实例化一张数据表 } ?> 第三步: 创建controller 在application\controllers目录文件下 <?php namespace app\controllers; use yii\web\Controller; use yii\data\Pagination; use app\models\Country; class CountryController extends Controller { public function actionIndex() { $query = Country::find();//调用活动记录,实例化contry表; $pagination = new Pagination([//调用对象分页,分页器和返回每一页数据; 'defaultPageSize'=>5, 'totalCount'=>$query->count(), ]); $countries = $query->orderBy('name') ->offset($pagination->offset)//从offset第几条记录到第pafination条记录为一页; ->limit($pagination->limit) ->all(); //传递数据,渲染模板 return $this->render('index',[ 'countries'=>$countries, 'pagination'=>$pagination, ]); } } ?> 第四步: 创建views视图文件: 在application\views\ 控制器名文件下\创建index.php <?php namespace app\controllers; use yii\web\Controller; use yii\data\Pagination; use app\models\Country; class CountryController extends Controller { public function actionIndex() { $query = Country::find();//调用活动记录,实例化contry表; $pagination = new Pagination([//调用对象分页,分页器和返回每一页数据; 'defaultPageSize'=>5, 'totalCount'=>$query->count(), ]); $countries = $query->orderBy('name') ->offset($pagination->offset)//从offset第几条记录到第pafination条记录为一页; ->limit($pagination->limit) ->all(); //传递数据,渲染模板 return $this->render('index',[ 'countries'=>$countries, 'pagination'=>$pagination, ]); } } ?> 最后访问localhost\index.php?r=contry/index
    转载请注明原文地址: https://ju.6miu.com/read-1138576.html
    最新回复(0)