雄辩的laravel:如何从 - > get()获取行数

JP *_*ter 33 php sql laravel eloquent

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

$wordlist = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)
                ->get();
Run Code Online (Sandbox Code Playgroud)

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

Tho*_*Kim 60

答案已更新

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

$wordCount = count($wordlist);
Run Code Online (Sandbox Code Playgroud)

如果您有wordlist模型,那么您可以使用Eloquent获取Collection,然后使用Collection的count方法.例:

$wordlist = Wordlist::where('id', '<=', $correctedComparisons)->get();
$wordCount = $wordlist->count();
Run Code Online (Sandbox Code Playgroud)

有关于让查询构建器在此处返回集合的讨论:https://github.com/laravel/framework/issues/10478

但是截至目前,查询构建器始终返回一个数组.

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

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

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

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

// Eloquent
$wordCount = Wordlist::where('id', '<=', $correctedComparisons)->count();
Run Code Online (Sandbox Code Playgroud)

  • 使用 where 子句直接访问 count() 比返回整个集合更快。例如,如果这是对整个用户表的计数,则仅计算它们可能会返回 1m 个结果,这将使用大量资源。 (7认同)
  • @Leon你是正确的。如果用户只需要计数,那么简单地查询计数就可以更快。此后,答案已经更新,以反映该内容和其他一些更改。 (2认同)

Ter*_*nal 21

 //Useing Eloquent
 $count = Model::count();    

 //example            
 $count1 = Wordlist::count();
Run Code Online (Sandbox Code Playgroud)


RJH*_*RJH 9

使用laravels计数方法可以更好地访问计数

$count = Model::where('status','=','1')->count();
Run Code Online (Sandbox Code Playgroud)

要么

$count = Model::count();
Run Code Online (Sandbox Code Playgroud)


小智 7

此外,您还可以获取刀片文件中的所有数据并进行计数。例如:

您在控制器中的代码

$posts = Post::all();
return view('post', compact('posts'));
Run Code Online (Sandbox Code Playgroud)

Blade 文件中的代码。

{{ $posts->count() }}
Run Code Online (Sandbox Code Playgroud)

最后,您可以看到您的帖子总数。