本文實(shí)例講述了Laravel框架執(zhí)行原生SQL語(yǔ)句及使用paginate分頁(yè)的方法。分享給大家供大家參考,具體如下:
1、運(yùn)行原生sql
public function getList($data){//獲取前端傳過(guò)來(lái)的參數(shù) $user = $data['userId']; $office = $data['officeId']; $key = $data['oneKeySearch'];//進(jìn)行模糊搜索和聯(lián)合查詢 $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 . '%")'; }//對(duì)前端傳回的字段進(jìn)行判斷,如果不為空則執(zhí)行條件查詢 if($user!=null){ $user='and a.userId='.$user; } if($office!=null){ $office='and a.officeId='.$office; }//自定義原生sql語(yǔ)句,%s可以傳參數(shù)到sql語(yǔ)句中,格式如下: $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);//執(zhí)行SQL語(yǔ)句 $results = DB::select($sqlTmp);//返回結(jié)果 return $results;}2、運(yùn)行查詢構(gòu)建器
public function getList($data){//獲取前端傳過(guò)來(lái)的參數(shù) $user = $data['userId']; $office = $data['officeId']; $key = $data['oneKeySearch'];/* * 1、表格使用別名:直接是 “表名 as table1" ,(下面是xxx1 as a) * 2、左連接:DB::table('表1') * ->leftJoin('表2', '表1.id', '=', '表2.外鍵關(guān)聯(lián)') * 3、因?yàn)槭褂昧塑泟h除,所以在查詢的時(shí)候要加上 ->whereNull('a.deleted_at') * 4、使用 DB::raw方法創(chuàng)建一個(gè)原生表達(dá)式,寫進(jìn)要查詢的字段名稱 * ->select(DB::raw('a.id,a.code,b.`realName` as userName,c.`name` as officeName')) *5、使用orderBy進(jìn)行排序 * */ $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)){},來(lái)判斷前端傳過(guò)來(lái)的參數(shù)是否為空,不為空則執(zhí)行條件查詢 if(!empty($user)){ $data = $data->where( 'a.userId',$user); } if(!empty($office)){ $data = $data->where( 'a.officeId',$office); } //使用 if(!empty(xxx)){},來(lái)判斷前端傳過(guò)來(lái)的參數(shù)是否為空,不為空則執(zhí)行模糊搜索和聯(lián)合查詢 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)進(jìn)行分頁(yè) $results=$data ->paginate(10); return $results;}希望本文所述對(duì)大家基于Laravel框架的PHP程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選