doucitao2944 2016-11-08 14:39
浏览 33
已采纳

从laravel模型中检索记录

I have a Laravel application, I have a database table with 780950 registers, so, when I retrieve this with eloquent it takes a long long time and then gives time exceeded error. Is there a way to retrieve for example the first 30 records? I tried with this:

mymodel::all()->take(30)->get();

But is the same. So then, I just put:

mymodel::where('id','<','30')->get();

And it works, but it's not what I want because I want to paginate and display all the records. So, I know that it's a lot of records, but if I can retrieve the first 30 and then with ajax retrieve another 30 more. So what is the best and more elegant way to achieve this in Laravel 5.3?

  • 写回答

2条回答 默认 最新

  • duanlu1922 2016-11-08 14:43
    关注

    When you do Model::all()->take(30)->get();, you're actually saying "retrieve all of the database records, then give me the first 30". So you'll be loading all 800,000 records just to grab the first 30.

    What you actually want to do, if you want pagination, is:

    $models = Model::paginate($perPage);
    

    The paginate() method will automatically determine the current page from the query strings in the URL, and give you back an object that you can pass to your views to paginate.

    <div class="container">
        @foreach ($models as $model)
            {{ $model->name }}
        @endforeach
    </div>
    
    {{ $models->links() }}
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?