最新消息: 新版网站上线了!!!

yii2原生态sql分页的实现方法

$totalCount =   0;
        $connection = \Yii::$app->getDb();
        $limit      =   10;
        $from       =   (isset($_GET['page'])) ? ($_GET['page']-1)*$limit : 0; // Match according to your query string
        $sql        =   'select * from {{%news}}';
        $command = $connection->createCommand($sql.' LIMIT '.$from.','.$limit);
        $count   = $connection->createCommand('SELECT COUNT(*) as total FROM ('.$sql.') a')->queryAll();
        $result         = $command->queryAll();
        $totalCount     =   $count[0]['total'];
        $pages = new  \yii\data\Pagination(['totalCount' => $totalCount, 'pageSize' => $limit]);
        return $this->render('join', [
            'models' => $result,
            'pages' => $pages,
        ]);

join.php

<?php
foreach ($models as $model) {

    // 在这里显示 $model,比如:

    echo $model['goods_name']."<br/>";

}

// display pagination

echo \yii\widgets\LinkPager::widget([

    'pagination' => $pages,

]);

转载请注明:谷谷点程序 » yii2原生态sql分页的实现方法