雄辩的laravel:如何从-> get()获取行数 [英] eloquent laravel: How to get a row count from a ->get()

查看:751
本文介绍了雄辩的laravel:如何从-> get()获取行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having a lot of trouble figuring out how to use this collection to count rows.

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

我尝试了adding->count(),但是没有用.我尝试做count($wordlist).我不确定在没有第二个请求作为a->count()方法的情况下该怎么做.

I have tried adding->count() but didn't work. I have tried doing count($wordlist). I'm not really sure what to do without needing a second request as a->count() method.

推荐答案

答案已更新

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

count is a Collection method. The query builder returns an array. So in order to get the count, you would just count it like you normally would with an array:

$wordCount = count($wordlist);

如果您有单词列表模型,则可以使用Eloquent来获取Collection,然后使用Collection的count方法.示例:

If you have a wordlist model, then you can use Eloquent to get a Collection and then use the Collection's count method. Example:

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

这里有/正在讨论让查询生成器返回集合: https://github.com/laravel/framework/issues/10478

There is/was a discussion on having the query builder return a collection here: https://github.com/laravel/framework/issues/10478

但是,到目前为止,查询生成器始终返回一个数组.

However as of now, the query builder always returns an array.

如上所示,查询构建器现在返回一个集合(不是数组).结果,JP Foster最初尝试执行的操作将起作用:

As linked above, the query builder now returns a collection (not an array). As a result, what JP Foster was trying to do initially will work:

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

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

However, as indicated by Leon in the comments, if all you want is the count, then querying for it directly is much faster than fetching an entire collection and then getting the count. In other words, you can do this:

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

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

这篇关于雄辩的laravel:如何从-&gt; get()获取行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆