php - Eloquent laravel : How to get a row count from a ->get()

标签 php sql laravel eloquent

我在弄清楚如何使用这个集合来计算行数时遇到了很多麻烦。

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
                ->get();

我尝试了 adding->count() 但没有奏效。我试过做 count($wordlist)。如果不需要第二个请求作为 a->count() 方法,我不确定该怎么做。

最佳答案

答案已更新

count 是一个 Collection 方法。查询生成器返回一个数组。因此,为了获得计数,您只需像通常使用数组一样计算它:

$wordCount = count($wordlist);

如果你有一个 wordlist 模型,那么你可以使用 Eloquent 获取一个 Collection,然后使用 Collection 的 count 方法。示例:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();

这里有/曾经讨论过让查询生成器返回一个集合:https://github.com/laravel/framework/issues/10478

但是到目前为止,查询构建器始终返回一个数组。

编辑:如上所述,查询构建器现在返回一个集合(不是数组)。因此,JP Foster 最初尝试做的事情将会奏效:

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->get();
$wordCount = $wordlist->count();

但是,正如 Leon 在评论中所指出的,如果您想要的只是计数,那么直接查询它比获取整个集合然后获取计数要快得多。换句话说,您可以这样做:

// Query builder
$wordCount = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
            ->count();

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();

关于php - Eloquent laravel : How to get a row count from a ->get(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33676576/

相关文章:

php - 使用ajax将数组发布到PHP

PHP - $_POST 变量与同名变量混合

sql - 使用 Sequelize 和 Express 更新链接表

iphone - 格式化存储在 SQLite3 中的文本数据

php - laravel Eloquent 查询关系

php - 找不到 autoload.php

javascript 或 htaccess 重写 url

php - 如何在谷歌标签管理器中实现谷歌有机标签

c# - 如何读取存储过程输出并将其作为列表返回

database - 如何在 laravel 中使用 Group by 查询?