后端代碼
public function actionList()
{
//接收查詢的關鍵字
$keywords = Yii::$app->request->get('keywords',"");
//獲取頁碼极景,參數需和Pagination中配置的參數一致
$page=Yii::$app->request->get('page');
$page=($page-1)>0?($page-1):0;
$pageSize=5;
$goods = Goods::find()
->where(['status'=>1])
->offset($page*$pageSize)
->limit($pageSize)
->orderBy('id');
//判斷查詢是否為空
if (!empty($keywords)) {
$goods->where("name like '%{$keywords}%' OR goods_no like '%{$keywords}%'");
}
//設置分頁配置
$config=[
'totalCount' => $goods->count(),
'defaultPageSize' => $pageSize,
];
//實例化分頁器,將配置參數傳入到Pagination中
$pages = new Pagination($config);
$categoryModel = GoodsCategory::find()->asArray()->all();
$brands = Brand::find()->asArray()->all();
$goods = $goods->all();
return $this->render('list',[
'category'=>$categoryModel,
'brands' =>$brands,
'goods' => $goods,
'pages' => $pages
]);
}
前端代碼
<tr>
<td align="right" nowrap="true" colspan="6">
<div id="turn-page">
<?=\yii\widgets\LinkPager::widget([
'pagination' => $pages,
'nextPageLabel' => '下一頁',
'prevPageLabel' => '上一頁',
'firstPageLabel' => '首頁',
'lastPageLabel' => '尾頁',
'maxButtonCount' => 5,
'hideOnSinglePage' => false,
])?>
</div>
</td>
</tr>