count() 方法 return 计算 eloquent 集合中的项目数还是直接从 sql 查询计算行数

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

我有以下两种方法来计算处于活动状态的帐户数。我想知道模型的 count() 方法是从数据库中获取行并计算返回对象的数量,还是仅通过应用 SQL count() 函数获取行数。还有下面两种方法是否相似?

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

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

如果您在查询生成器上使用它,那么它将执行一个 SQL 查询,但如果您在 Laravel 集合上使用它,它将在该集合上执行。

根据您的示例,这将是一个查询:

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

但是,例如,这将首先获取结果(returns 一个集合)然后计算集合中的项目:

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

也许更直观:

$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']);