我是靠谱客的博主 开朗过客,这篇文章主要介绍Laravel执行原生SQL语句及使用paginate分页,现在分享给大家,希望可以做个参考。

1、运行原生sql

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
ublic 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、运行查询构建器

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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; }


最后

以上就是开朗过客最近收集整理的关于Laravel执行原生SQL语句及使用paginate分页的全部内容,更多相关Laravel执行原生SQL语句及使用paginate分页内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(473)

评论列表共有 0 条评论

立即
投稿
返回
顶部