dtzh131555 2017-04-06 14:44
浏览 105
已采纳

为什么求和大数据不起作用? (Laravel 5.3)

My code, you can see this below :

public function total()
{
    $query = User::limit(100000)->get();
    $total = $query->sum('total');
    dd($total);
}

The result of dd($total) not display or empty

But when I change limit(50000), it display the result

Why it does not work if limit(100000)?

Note :

In firefox browser, it does not display anything

In chrome browser, it display error :

This page isn’t working

myshop.dev is currently unable to handle this request. HTTP ERROR 500

  • 写回答

1条回答 默认 最新

  • dongxiaoguang9108 2017-04-06 14:51
    关注

    When you call get, you are fetching all this records from the database. And then performing the sum with php. You are probably having a timeout when fetching that much records from the database.

    Why don't you perform the sum in the database, and then fetch the result?

    public function total()
    {
        $total = User::limit(100000)->sum('total');
        dd($total);
    }
    

    ----- edit -----

    When you perform:

    $query = User::limit(100000)->get();

    The $query variable actually holds the result set of the query select * from user limit 100000. The result set its a collection (see collect), then you are performing a sum on the server-side, something equivalent to:

    $sum = 0;
    foreach ($user in $query) {
        $sum = $sum + $user->total;
    }
    

    It's better to perform the sum in the database using the proper aggregate function.

    $total = User::limit(100000)->sum('total'); would translate to:

    select SUM(total) from user limit 1000000

    If the result is 0, probably all your result set for the column total is actually 0.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 对于squad数据集的基于bert模型的微调
  • ¥15 为什么我运行这个网络会出现以下报错?CRNN神经网络
  • ¥20 steam下载游戏占用内存
  • ¥15 CST保存项目时失败
  • ¥15 树莓派5怎么用camera module 3啊
  • ¥20 java在应用程序里获取不到扬声器设备
  • ¥15 echarts动画效果的问题,请帮我添加一个动画。不要机器人回答。
  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事: