Tp5.1 join的封裝以及多表查詢
阿新 • • 發佈:2021-08-09
封裝程式碼:
/** * 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標準引數格式 * returnView Code*/ 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; }
使用:(三表查詢)
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