douhong6187 2017-05-05 15:57
浏览 77

Laravel分页与原始查询

I'm using a raw SQL query in Laravel, because it was easier to me at the beginning to make complex queries, so I used them like that.

Now I want to get a list of comments of an user 7, and I would like to paginate the comments, in 5.

That's what I have:

$comments = DB::select( DB::raw("SELECT users.name,  reviews.comment, reviews.comment_score FROM reviews JOIN users WHERE reviews.user_id = :logged_user;")
   ,array('logged_user' => $user_id,));

So this query depends on the user which is consulting the view, receives a variable.

All I see for pagination is with Eloquent queries, and I don't find any clear usage for this.

If I add '->paginate(5)' at the end of the last parenthesis, or later to the variable like $comments->paginate(5); I get a:

Error: Call to a member function paginate() on array

Some light on this??

Thanks a lot! =)

  • 写回答

1条回答 默认 最新

  • dongqiyou0303 2017-05-05 16:14
    关注

    You do something like this for pagination.

    $perPage = $request->input("per_page", 10);
    $page = $request->input("page", 1);
    $skip = $page * $perPage;
     if($take < 1) { $take = 1; }
    if($skip < 0) { $skip = 0; }
    
    $comments = DB::select( DB::raw("SELECT users.name,  reviews.comment, reviews.comment_score FROM reviews JOIN users WHERE reviews.user_id = :logged_user;"),array('logged_user' => $user_id,));
    
    $totalCount = $comments->count();
    $results = $comments
        ->take($perPage)
        ->skip($skip)
        ->get();
    $paginator = new \Illuminate\Pagination\LengthAwarePaginator($results, $totalCount, $take, $page);
    
    return $paginator;
    

    Hope it will help you!

    评论

报告相同问题?

悬赏问题

  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题
  • ¥15 (标签-Python|关键词-socket)
  • ¥15 keil里为什么main.c定义的函数在it.c调用不了