简体   繁体   English

count()方法是否返回雄辩的集合中的项目计数或直接从sql查询中计数行

[英]Does count() method return count of items in eloquent collection or counts rows directly from sql query

I have the following two methods to count number of accounts that have active status. 我有以下两种方法来计算具有活动状态的帐户数量。 I want to know whether the count() method for model fetches rows from database and count the number of returned objects or will it just fetch row counts by applying SQL count() function. 我想知道模型的count()方法是从数据库中获取行并计算返回对象的数量,还是仅通过应用SQL count()函数来获取行数。 And also if the following two methods are similar or not? 而且以下两种方法是否相似?

Account::select(DB::raw('count(*) as count'))->where('status','active')->get()->count

Account::where('status','active')->count()

If you use it on a query builder, then it will perform an SQL query, but if you use it on a Laravel collection, it will perform it on the collection. 如果在查询生成器上使用它,则它将执行SQL查询,但如果在Laravel集合上使用它,则将在集合上执行它。

From your examples, this one will be a query: 从您的示例中,这将是一个查询:

Account::where('status','active')->count();
// SQL performed: SELECT count(*) FROM accounts WHERE status = active;

But this for example, would first fetch the results (which returns a collection) and then count the items in the collection: 但是,例如,这将首先获取结果(返回一个集合),然后计算该集合中的项目:

Account::where('status','active')->get()->count();
// SQL performed: SELECT * FROM accounts WHERE status = active;

Maybe more intuitive: 也许更直观:

$accounts = Account::where('status', 'active')->get();
// $accounts is now a collection of accounts SQL to get them was:
// select * from accounts where status = active;

// Then you can do this and it will be the same as performing count($accounts)
$count = $accounts->count();
// Same as doing this (except the items in the collection are different)
$count = collect(['some', 'elements', 'in the', 'collection']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM