yii 分页查询

控制器

<?php

namespace backendcontrollers;
use appmodelsComment;
use appmodelsCommentstatus;
use yiidataPagination;

class CommentController extends yiiwebController
{
    public function actionIndex()
    {
        // 创建一个 DB 查询来获得所有 status 为 2 的数据
        $query = Comment::find()->where(['status'=>2]);
        // 统计总数(但是还没有从数据库取数据)
        $count = $query->count();
        // 使用总数来创建一个分页对象 TotalCount指定数据条目的总数 pageSize指定每页包含多少数据条目
        $page = new Pagination(['totalCount'=>$count,'pageSize'=>2]);
        // 使用分页对象来填充 limit 子句并取得数据
        $comments = $query->offset($page->offset)
            ->limit($page->limit)
            ->all();

        return $this->renderPartial('index',[
            'model' => $comments,
            'pages' => $page,
        ]);
    }
}

模型

<?php

namespace appmodels;

use Yii;

class Comment extends yiidbActiveRecord
{
    public function getCommentStatus()
    {
        return $this->hasOne(Commentstatus::className(),['id'=>'status']);
    }
}
<?php

namespace appmodels;

use Yii;

class Commentstatus extends yiidbActiveRecord
{
    public function getComment()
    {
        return $this->hasMany(Comment::className(),['status'=>'id']);
    }
}

HTML页面(index.php)

<?php
use yiiwidgetsLinkPager;
?>
<?php foreach ($model as $k=>$v){?>
    <?= $v->id;?>
    <?= $v->content;?>
    <?= $v->commentStatus->name;?><!--通过模型关联查询的取得的状态名称-->
<?php }?>

<!--分页小部件-->
<?=
LinkPager::widget([
    'pagination' => $pages,
]);
?>

 MySQL数据表

CREATE TABLE `commentstatus` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`position` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

CREATE TABLE `comment` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`content` text COLLATE utf8_unicode_ci NOT NULL,
`status` int(11) NOT NULL,
`create_time` int(11) DEFAULT NULL,
`userid` int(11) NOT NULL,
`email` varchar(128) COLLATE utf8_unicode_ci NOT NULL,
`url` varchar(128) COLLATE utf8_unicode_ci DEFAULT NULL,
`post_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_comment_post` (`post_id`),
KEY `FK_comment_user` (`userid`),
KEY `FK_comment_status` (`status`),
CONSTRAINT `FK_comment_post` FOREIGN KEY (`post_id`) REFERENCES `post` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_comment_status` FOREIGN KEY (`status`) REFERENCES `commentstatus` (`id`) ON DELETE CASCADE,
CONSTRAINT `FK_comment_user` FOREIGN KEY (`userid`) REFERENCES `user` (`id`) ON DELETE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=96 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

原文地址:https://www.cnblogs.com/clubs/p/9494687.html