yii框架中的兩表聯查+分頁

view視圖部分

<?php
use yii\widgets\LinkPager;
foreach($models as $k=>$v){
    echo "<tr>";
    echo "<td>".$v['u_id']."</td>";
    echo "<td>".$v['u_name']."</td>";
    echo "<td>".$v['u_state']."</td>";
    echo "</tr>";
}
echo LinkPager::widget([
    'pagination' => $pages,
]);
?>


控制器部分頁

<?php
use yii\data\Pagination;
public function actionList()
{
    $test=new TestForm();    //實例化model模型
    $arr=$test->find();
    //$countQuery = clone $arr;
    $pages = new Pagination([
        //'totalCount' => $countQuery->count(),
        'totalCount' => $arr->count(),
        'pageSize'   => 2   //每頁顯示條數
    ]);
    $models = $arr->offset($pages->offset)
        ->limit($pages->limit)
        ->all();
    return $this->render('list', [
        'models' => $models,
        'pages'  => $pages
    ]);
}
?>


控制器兩表聯查+分頁  yii控制器中的方法

    public function actionHuihualist(){
        $cla_id=yii::$app->request->get('cla_id');
// $cla_id=3;//測試數據
        $test=new Huihua();    //實例化model模型
        $arr=$test->find();
        //$countQuery = clone $arr;
        $pages = new Pagination([
            //'totalCount' => $countQuery->count(),
            'totalCount' => $arr->count(),
            'pageSize'   => 2   //每頁顯示條數
        ]);
        $models = $arr->select('*')  //查詢的對象指向
            ->innerJoin('student','huihua.h_stu_id=student.stu_id') //兩表聯查
            ->where(['h_cla_id'=>$cla_id]) //查詢的條件
            ->offset($pages->offset)  //每頁的偏移量
            ->limit($pages->limit)    //每頁的條數
            ->asArray()               //轉化成數組
            ->all();
        return $this->render('huihualist', [
            'data' => $models,  //把頁面要循環的值傳過去,data是名字,$models是查出來的值
            'pages'  => $pages,
            // 'data'=>$data
        ]);
    }

        //未分頁的兩表聯查
        // $h=new Huihua();
        // $data=$h->find()->select('*')->innerJoin('student','huihua.h_stu_id=student.stu_id')->where(['h_cla_id'=>$cla_id])->asArray()->all();
        // return $this->render('huihualist',['data'=>$data]);



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章