雄辩的laravel:如何从-> get()获取行数
技术问答
295 人阅读
|
0 人回复
|
2023-09-14
|
当我发现如何使用这一集的数行时,我遇到了很多麻烦。3 o7 F0 K2 g: }' Q1 \& M" t7 d
$wordlist = \DB::table('wordlist')->where('id','get();我试过,adding->count()但是没用。我试过。count($wordlist)。我不确定没有第二个请求。a->count()如何做方法。
* I# ]3 S D, ^' ]' C+ \0 } 1 x" y, ^( P. O9 t: N& h' K
解决方案:
! k, U$ U1 D* o 答案已更新5 ?2 p* p7 C5 Q8 y3 { U
count是一个Collection方法。查询构建器返回数组。因此,为了获得计数,您只需要像通常使用数组一样计数:
, V7 i. w) [/ F8 x, \* e. o; X$wordCount = count($wordlist);如果有单词列表模型,可以使用Eloquent来获取Collection,然后使用Collection的count例子:5 H- T: L1 ]" Z# w1 y
$wordlist = Wordlist::where('id','get();$wordCount = $wordlist->count();这里有/正在讨论让查询生成器返回一个集合:https% g* Z5 H B- S
:
# J$ R8 L( i7 O8 [//github.com/laravel/framework/issues/10478; f& p( w! A% s; |; |" r& z
但到目前为止,查询生成器总是返回一个数组。: M3 E; q. [; I1 _7 i3 r
编辑:以上链接,查询生成器现在返回集合(不是数组)。JP Foster最初尝试执行的操作将起作用:
' a* y# L$ D( Y! p+ S$wordlist = \DB::table('wordlist')->where('id','get();$wordCount = $wordlist->count();但是,正如Leon评论中指出,如果只需要计数,直接查询比获得整个集合和计数要快得多。换句话说,您可以执行以下操作:& i; B9 f/ P% p
// Query builder$wordCount = \DB::table('wordlist')->where('id','count();// Eloquent$wordCount = Wordlist::where('id','count();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; |
|
|
|
|
|