yii2实现后端分页和模糊查询

注:这里说的是前后端分离的方式,前端可以用vue+element,不管用什么,只要能把需要的参数传给后端就OK

1.前端需要传的主要参数包括:

listQuery: { //动态请求table数据时传递的参数
        page_no: 1, //页码
        page_size: 10,//每页显示条数
        role: null,//角色--选填
        username: null,//用户名--选填
        partantuser: getUserName(),//上级用户名--选填
      },

2.下面开始后端获取参数并进行模糊查询和分页后返回

在controller中获取到参数并传给model进行处理,然后获取到数据并返给前端

public function actionGetalluser()
    {
        $request = Yii::$app->request;
        $post = $request->post();
        $username = $request->post('username');
        $role = $request->post('role');
        $page_no = $request->post('page_no',1);
        $page_size = $request->post('page_size');
        $partantuser = $request->post('partantuser');
        $partant = userinfo::getusermsg($partantuser);//获取到上级用户的信息
        $userinfo = [
            'username' => $username,
            'role' => $role,
            'page_no' => $page_no,
            'page_size' => $page_size,
            'partantid' => $partant['id']
        ];
        $getallusermsg = userinfo::getallusermsg($userinfo); //将从前端获取到的数据传递给model
        if ($getallusermsg) {
            echo json_encode($getallusermsg);
        } else {
            echo json_encode(['code' => 201,'data' => '','message' => '获取用户信息失败!']);
        }
    }

model中获取到controller中传递的参数,并从数据库中查询并以分页和模糊查询的方式传递给controller

public static function getallusermsg($userinfo)
	{
        $query = self::find()->where(['partantid' => $userinfo['partantid']]);
        if ($userinfo['username']) {
            $query->andWhere(['like', 'username', $userinfo['username']]); //link为模糊查询
        }
        if ($userinfo['role']) {
            $query->andWhere(['role' => $userinfo['role']]);
        }
        //进行后端分页
        $startpage = ($userinfo['page_no'] -1) * $userinfo['page_size'];
        $count = $query->offset($startpage)->count();
        $data = $query->limit($userinfo['page_size'])->offset($startpage)->asArray()->all();
        $dataall = [
            'code' => 200,
            'data' => [
                'count' => (int)$count,
                'data' => $data,
                'page_count' =>ceil($count/$userinfo['page_size'])
            ],
            'message' => '获取用户信息成功!'
        ];
        return $dataall;
	}

哈哈,是不是很简单!

你可能感兴趣的:(yii2实现后端分页和模糊查询)