laravel ->count() 与 ->get()->count()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47608873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 17:02:13  来源:igfitidea点击:

laravel ->count() vs ->get()->count()

laraveleloquent

提问by Chris

Why are the two statement below behaving differentlY? The first returns 3 the second returns 1 for $progress. I thought that the first aggregates on the DB and the second on the server. So they should still return the same value.

为什么下面的两个语句表现不同?第一个返回 3,第二个返回 $progress 的 1。我认为第一个聚合在数据库上,第二个聚合在服务器上。所以它们仍然应该返回相同的值。

$progress = $this->user->userActivities()->select('date')
                ->groupBy('date')
                ->get()->count();

$progress =  $this->user->userActivities()->select('date')
                ->groupBy('date')
                ->count();

回答by Alexey Mezenin

->get()->count()will load Eloquent model objects into memory and then will count those.

->get()->count()将 Eloquent 模型对象加载到内存中,然后计算这些对象。

->count()will use DB aggregate function, so it will definitely be more efficient:

->count()将使用 DB 聚合函数,所以它肯定会更有效率:

select count(*) as aggregate ...

回答by Mikke Baldonado

$count = Model::all()->count();
return view('home',compact('count'));

this will function for laravel 6;

这将适用于 laravel 6;

回答by Lajos Arpad

The first counts the number of returned records, the second counts the records and returns the number. If you are using a paging of 10, for example, then the first will yield 10 and the second the actual number if the number of mathcing elements is greater than 10.

第一个计算返回记录的数量,第二个计算记录并返回数量。例如,如果您使用 10 的分页,那么如果数学元素的数量大于 10,则第一个将产生 10,第二个将产生实际数字。

回答by Gold Chess

Use ->get()->count()is wrong. I used ->get()->count()in my web app and when my database records have more than 80000 records I get error 500 in my app.

->get()->count()错了。我->get()->count()在我的网络应用程序中使用过,当我的数据库记录有超过 80000 条记录时,我的应用程序中出现错误 500。