crowprince 2016-08-04 17:40:29 7412次浏览 0条评论 4 1 0

原文:http://blog.csdn.net/lx_96/article/details/52121067
1.控制器中的代码实现:
1.1方法一:

public function actionPage(){
    $query = User::find()->where(['name'=>'admin']);
    $countQuery = clone $query;
    $pages = new Pagination(['totalCount'=>$countQuery->count(),'defaultPageSize'=>1]);//设置数据总量与每页数据大小(几条)
    $models = $query->offset($pages->offset)//偏移量
                    ->limit($pages->limit)//此处获取的就是pageSize的值
                    ->all();
    return $this->render('page',[
        'models'=>$models,
        'pages'=>$pages,
    ]);
}

1.2方法二:
可以自定义一个方法,用来传递分页所需的参数方法如下(可以为其他方法公用分页):

/*
* 其中config的参数有:
* pageSize:设置每页大小
* order:数据的排序
* rows:返回的数组中数据对象的键名
* pages:返回的数组中分页的对象的键名
*/
public function getPageRows($query,$config=[]){
	$countQuery = clone $query;
	$pages = new Pagination(['totalCount'=>$countQuery->count()]);
	if(isset($config['pageSize']))
	{
		$pages->setPageSize($config['pageSize'],true);
	}
	$rows = $query->offset($pages->offset)->limit($pages->limit);
	if(isset($config['order'])){
		$rows = $rows->orderBy($config['order']);
	}
	$rows = $rows->all();
	$rowsLable = 'rows';
	$pagesLable = 'pages';
	if(isset($config['rows'])){
		$rowsLable = $config['rows'];
	}
	if(isset($config['pages'])){
		$pagesLable = $config['pages'];
	}
	$ret = [];
	$ret[$rowsLable] = $rows;
	$ret[$pagesLable] = $pages;
	return $ret;
}

控制器中代码如下:

public function actionPage(){	
	$query = User::find()->where(['name'=>'admin']);
	$locals = $this->getPageRows($query,['order'=>'id desc','pageSize'=>2,'rows'=>'models']);
	return $this->render('page',$locals);
}

2.视图中的代码如下:

<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016/7/27
 * Time: 15:45
 */
use yii\widgets\LinkPager;
$id = 5;
$count = 1;
if($this->beginCache($id,['duration'=>3,])){
foreach($models as $item){
?>
<p><?php echo $item["introduce"];?></p>
<?php }
    echo LinkPager::widget(['pagination'=>$pages]);//页码
    $this->endCache();
}
?>

好了完整的分页功能好了,可以使用了!
原文:http://blog.csdn.net/lx_96/article/details/52121067

觉得很赞
    没有找到数据。
您需要登录后才可以评论。登录 | 立即注册