欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

Laravel框架执行原生SQL语句及使用paginate分页的方法

程序员文章站 2023-11-02 13:50:52
本文实例讲述了laravel框架执行原生sql语句及使用paginate分页的方法。分享给大家供大家参考,具体如下: 1、运行原生sql public func...

本文实例讲述了laravel框架执行原生sql语句及使用paginate分页的方法。分享给大家供大家参考,具体如下:

1、运行原生sql

public 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、运行查询构建器

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相关内容感兴趣的读者可查看本站专题:《laravel框架入门与进阶教程》、《php优秀开发框架总结》、《php面向对象程序设计入门教程》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总

希望本文所述对大家基于laravel框架的php程序设计有所帮助。