1. 程式人生 > >Laravel中執行原生SQL語句,使用paginate分頁

Laravel中執行原生SQL語句,使用paginate分頁

1、執行原生sql
public function getList($data){
//獲取前端傳過來的引數
    $user = $data['userId'];
    $office = $data['officeId'];
    $key = $data['oneKeySearch'];

//進行模糊搜尋和聯合查詢
    $where = 'and 1=1 ';
    if($key!=null) {
        $where.= ' and ( a.code like "%' . $key . '%"';
        $where.= ' or b.name like "%' . $key . '%"';
        $where.= ' or c.name like "%' . $key . '%")';
    }
//對前端傳回的欄位進行判斷,如果不為空則執行條件查詢
    if($user!=null){
        $user='and a.userId='.$user;
    }

    if($office!=null){
        $office='and a.officeId='.$office;
    }
//自定義原生sql語句,%s可以傳引數到sql語句中,格式如下:
    $sqlTmp=sprintf('select a.id,a.code,a.attendanceRate,a.statisticTime,
                        b.`realName` as userName,c.`name` as officeName
                        from xxxa1
                        LEFT  JOIN xxx2 b ON a.userId=b.id
                        LEFT  JOIN xxx3 c ON a.officeId=c.id
       where  a.deleted_at is null and 1=1 %s  %s %s ORDER BY a.code
       ', $where,$office,$user);

//執行SQL語句
    $results = DB::select($sqlTmp);
//返回結果
    return $results;
}

2、執行查詢構建器
public function getList($data){
//獲取前端傳過來的引數
    $user = $data['userId'];
    $office = $data['officeId'];
    $key = $data['oneKeySearch'];

/*
 * 1、表格使用別名:直接是  “表名  as table1" ,(下面是xxx1  as a)
 * 2、左連線:DB::table('表1')
 *               ->leftJoin('表2', '表1.id', '=', '表2.外來鍵關聯')
 * 3、因為使用了軟刪除,所以在查詢的時候要加上 ->whereNull('a.deleted_at')
 * 4、使用 DB::raw方法建立一個原生表示式,寫進要查詢的欄位名稱
 *       ->select(DB::raw('a.id,a.code,b.`realName` as userName,c.`name` as officeName'))
 *5、使用orderBy進行排序
 *
 */

         $data=DB::table('biz_attendance_sta as a')
             ->leftJoin('sys_user as b', 'b.id', '=', 'a.userId')
             ->leftJoin('sys_office as c', 'c.id', '=', 'a.officeId')
            ->select(DB::raw('a.id,a.code,a.attendanceRate,a.statisticTime,
                            b.`realName` as userName,c.`name` as officeName'))
             ->whereNull('a.deleted_at')
             ->orderBy('a.code', 'desc');
 //使用 if(!empty(xxx)){},來判斷前端傳過來的引數是否為空,不為空則執行條件查詢
         if(!empty($user)){
             $data = $data->where( 'a.userId',$user);
         }
        if(!empty($office)){
            $data = $data->where( 'a.officeId',$office);
        }

 //使用 if(!empty(xxx)){},來判斷前端傳過來的引數是否為空,不為空則執行模糊搜尋和聯合查詢
        if (!empty($key)) {
            $data = $data->where(function ($query) use ($key) {
                $query->where('a.code', 'like', "%{$key}%")
                    ->orWhere('b.name', 'like', "%{$key}%")
                    ->orWhere('c.name', 'like', "%{$key}%");
            });
        }

//使用->paginate(10)進行分頁
        $results=$data ->paginate(10);


        return $results;
    }