Laravel框架執(zhí)行原生SQL語句及使用paginate分頁的方法
本文實例講述了Laravel框架執(zhí)行原生SQL語句及使用paginate分頁的方法。分享給大家供大家參考,具體如下:
1、運行原生sql
public function getList($data){ //獲取前端傳過來的參數(shù) $user = $data['userId']; $office = $data['officeId']; $key = $data['oneKeySearch']; //進行模糊搜索和聯(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 . '%")'; } //對前端傳回的字段進行判斷,如果不為空則執(zhí)行條件查詢 if($user!=null){ $user='and a.userId='.$user; } if($office!=null){ $office='and a.officeId='.$office; } //自定義原生sql語句,%s可以傳參數(shù)到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); //執(zhí)行SQL語句 $results = DB::select($sqlTmp); //返回結(jié)果 return $results; }
2、運行查詢構(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、因為使用了軟刪除,所以在查詢的時候要加上 ->whereNull('a.deleted_at') * 4、使用 DB::raw方法創(chuàng)建一個原生表達式,寫進要查詢的字段名稱 * ->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)){},來判斷前端傳過來的參數(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)進行分頁 $results=$data ->paginate(10); return $results; }
更多關(guān)于Laravel相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Laravel框架入門與進階教程》、《php優(yōu)秀開發(fā)框架總結(jié)》、《php面向?qū)ο蟪绦蛟O(shè)計入門教程》、《php+mysql數(shù)據(jù)庫操作入門教程》及《php常見數(shù)據(jù)庫操作技巧匯總》
希望本文所述對大家基于Laravel框架的PHP程序設(shè)計有所幫助。
相關(guān)文章
PHP+FastCGI+Nginx配置PHP運行環(huán)境
Nginx不支持對外部程序的調(diào)用,所以必須通過FastCGI接口實現(xiàn)對外部程序的調(diào)用從而實現(xiàn)對客戶端動態(tài)頁面請求的處理。2014-08-08詳解Laravel設(shè)置多態(tài)關(guān)系模型別名的方式
這篇文章主要介紹了Laravel 中簡單設(shè)置多態(tài)關(guān)系模型別名的方式,需要的朋友可以參考下2019-10-10Laravel使用PHPQRCODE實現(xiàn)生成帶有LOGO的二維碼圖片功能示例
這篇文章主要介紹了Laravel使用PHPQRCODE實現(xiàn)生成帶有LOGO的二維碼圖片功能,涉及php引入PHPQRCODE類生成二維碼圖片的相關(guān)調(diào)用與設(shè)置操作技巧,需要的朋友可以參考下2017-07-07