温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

Laravel框架中怎么使用paginate实现分页

发布时间:2021-07-19 14:43:39 来源:亿速云 阅读:208 作者:Leah 栏目:开发技术

今天就跟大家聊聊有关Laravel框架中怎么使用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框架中怎么使用paginate实现分页有进一步的了解吗?如果还想了解更多知识或者相关内容,请关注亿速云行业资讯频道,感谢大家的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI