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 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题