雄辩的laravel:如何从-> get()获取行数
技术问答
808 人阅读
|
0 人回复
|
2023-09-14
|
当我发现如何使用这一集的数行时,我遇到了很多麻烦。% w/ E+ K; _. R2 x0 s& r
$wordlist = \DB::table('wordlist')->where('id','get();我试过,adding->count()但是没用。我试过。count($wordlist)。我不确定没有第二个请求。a->count()如何做方法。
) y8 L& d) e4 d2 c9 A% s + K/ ?) m; j2 Z# U# y
解决方案: 8 }9 Y, O* q( @) x1 f( j8 m
答案已更新
0 B. }% W! o. Ucount是一个Collection方法。查询构建器返回数组。因此,为了获得计数,您只需要像通常使用数组一样计数:# H F1 [6 q! Y. o
$wordCount = count($wordlist);如果有单词列表模型,可以使用Eloquent来获取Collection,然后使用Collection的count例子:3 W5 e5 T. _# F: u
$wordlist = Wordlist::where('id','get();$wordCount = $wordlist->count();这里有/正在讨论让查询生成器返回一个集合:https
K' y& d) M9 c9 L: `:+ s# d9 c b7 E
//github.com/laravel/framework/issues/10478
! M' b; a* N" h* @ w3 l3 B6 J! C但到目前为止,查询生成器总是返回一个数组。4 H# x E7 C7 v$ k+ E" U- H
编辑:以上链接,查询生成器现在返回集合(不是数组)。JP Foster最初尝试执行的操作将起作用:
1 f" Z! g9 f: v; J$wordlist = \DB::table('wordlist')->where('id','get();$wordCount = $wordlist->count();但是,正如Leon评论中指出,如果只需要计数,直接查询比获得整个集合和计数要快得多。换句话说,您可以执行以下操作:
7 ? Y. B1 m4 y( D1 F2 _// Query builder$wordCount = \DB::table('wordlist')->where('id','count();// Eloquent$wordCount = Wordlist::where('id','count();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
|
|
|
|
|