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

为什么求和大数据不起作用? (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

图片转代码服务由CSDN问答提供 功能建议

我的代码,您可以在下面看到:

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

dd($ total)的结果未显示或为空

但是当我更改 limit(50000)时,它会显示结果

如果 limit(100000),为什么它不起作用?

注意:

在Firefox浏览器中,它不显示任何内容

在Chrome浏览器中,它显示 错误:

此页面无法正常工作

myshop.dev当前无法处理此请求。 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.

    已采纳该答案
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题