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;
}
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ù)庫操作技巧匯總》