答案已更新
count
是一个收集方法。查询生成器返回一个数组。因此,为了获得计数,您只需像通常使用数组一样计算它:
$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();
直接获取行数
使用雄辩
//Useing Eloquent
$count = Model::count();
//example
$count1 = Wordlist::count();
使用查询生成器
//Using query builder
$count = \DB::table('table_name')->count();
//example
$count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();
最好使用 laravel 计数方法访问计数
$count = Model::where('status','=','1')->count();
或者
$count = Model::count();
此外,您可以获取刀片文件中的所有数据和计数。例如:
您在控制器中的代码
$posts = Post::all();
return view('post', compact('posts'));
您在刀片文件中的代码。
{{ $posts->count() }}
最后,您可以看到您的帖子总数。
不定期副业成功案例分享