Tp5.1 join的封装以及多表查询

封装代码:

 /**
     * join查询
     *
     * @param $request
     * @param $data //存放查询条件、字段、排序的 数组
     * @param $data ['join']      连接对象  " 表名 b "
     * @param $data ['condition'] 连接条件  " a.id = b.classId "
     * @param $data ['where']     查询条件  " [ a.id => $id ,b.name => 'test' ] "
     * @param $data ['field']     查询字段  " a.id,title,class_id , b.id,name "
     * @param $data ['order']     排序      " a.id desc "
     * @param $type //left right join
     * @param $return 1: 纯数据格式  2: api标准参数格式
     * return
     */
    public function _joinList($request, $data, $type = '', $return = 2)
    {
        $page = $request->page ?? 1;
        $limit = $request->limit ?? 5;

        $list = self::alias('a')                     //主表为 a
        ->join($data['join'], $data['condition'] ?? '', $type)
            ->where($data['where'] ?? ['a.status' => 1])
            ->field($data['field'])
            ->order($data['order'] ?? 'a.id desc')
            ->select()->toArray();

        $start = $limit * ($page - 1);
        $data = array_slice($list, $start, $limit);   // 第n页 第n条 数据
        $total = count($list);

        if (!$total)
            failApi('无数据', 0, 204)->send();

        if ($return == 2)
            return arrayApi(count($data), $data, 'success!!', 'fail!!', $total);
        else
            return $data;
    }
View Code

 

使用:(三表查询)

public function list()     // 展示
    {
        $admin = new Admin();

        $data = [
            'join' => [['role b','a.role_id = b.id','right'],['admin_log c','a.id = c.admin_id','right']],
            'field' => 'a.username,account,b.title,c.content,c.create_time',
            'order' => 'c.create_time desc'
        ];
        $this->request->limit = 10;
        $res = $admin->_joinList($this->request, $data);
        return json($res);
View Code

 

posted @ 2021-08-09 20:02  jaychou、  阅读(187)  评论(0编辑  收藏  举报