本文實(shí)例講述了Laravel框架執(zhí)行原生SQL語(yǔ)句及使用paginate分頁(yè)的方法。分享給大家供大家參考,具體如下:
1、運(yùn)行原生sql
public function getList($data){ //獲取前端傳過來的參數(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){ //獲取前端傳過來的參數(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)){},來判斷前端傳過來的參數(shù)是否為空,不為空則執(zhí)行條件查詢 if(!empty($user)){ $data = $data->where( 'a.userId',$user); } if(!empty($office)){ $data = $data->where( 'a.officeId',$office); } //使用 if(!empty(xxx)){},來判斷前端傳過來的參數(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; }
更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進(jìn)階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計(jì)入門教程》、《php+mysql數(shù)據(jù)庫(kù)操作入門教程》及《php常見數(shù)據(jù)庫(kù)操作技巧匯總》
希望本文所述對(duì)大家基于Laravel框架的PHP程序設(shè)計(jì)有所幫助。
標(biāo)簽:廊坊 崇左 白銀 太原 鄂州 衡陽(yáng) 辛集 綏化
巨人網(wǎng)絡(luò)通訊聲明:本文標(biāo)題《Laravel框架執(zhí)行原生SQL語(yǔ)句及使用paginate分頁(yè)的方法》,本文關(guān)鍵詞 Laravel,框架,執(zhí)行,原生,SQL,;如發(fā)現(xiàn)本文內(nèi)容存在版權(quán)問題,煩請(qǐng)?zhí)峁┫嚓P(guān)信息告之我們,我們將及時(shí)溝通與處理。本站內(nèi)容系統(tǒng)采集于網(wǎng)絡(luò),涉及言論、版權(quán)與本站無關(guān)。