我很难弄清楚如何使用这个集合来计算行数。
$wordlist = 'DB::table('wordlist')->where('id', '<=', $correctedComparisons)
->get();
我尝试过adding->count()
,但没有成功。我试过做count($wordlist)
。我真的不知道在不需要第二个请求作为a->count()
方法的情况下该怎么办。
答案已更新
count
是一种Collection方法。查询生成器返回一个数组。因此,为了得到计数,你只需要像通常使用数组一样进行计数:
$wordCount = count($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();
直接获取行计数
使用Eloquent
//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();
使用laravels计数方法访问计数更好
$count = Model::where('status','=','1')->count();
或
$count = Model::count();
此外,您还可以获取刀片文件中的所有数据和计数。例如:
控制器中的代码
$posts = Post::all();
return view('post', compact('posts'));
刀片文件中的代码。
{{ $posts->count() }}
最后,你可以看到你的帖子总数。
//控制器$count = Post::count(); return view('post', compact('count'));
//叶片{{$count}}
或//控制器$posts = Post::all(); return view('post', compact('posts'));
//叶片{{count($posts)}}