回答

收藏

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

技术问答 技术问答 752 人阅读 | 0 人回复 | 2023-09-14

当我发现如何使用这一集的数行时,我遇到了很多麻烦。
+ {, K0 W! X% U9 o" m. ~$wordlist = \DB::table('wordlist')->where('id','get();我试过,adding->count()但是没用。我试过。count($wordlist)。我不确定没有第二个请求。a->count()如何做方法。% B' X7 B4 L# c* E" g& X' c* i
                                                               
/ D8 R+ b& c8 L) n1 }: j    解决方案:                                                               
6 @: |& Q% i( \                                                                答案已更新$ y3 T3 r4 d5 J# O$ Q- q( K8 T: `
count是一个Collection方法。查询构建器返回数组。因此,为了获得计数,您只需要像通常使用数组一样计数:
0 c$ K! M9 r4 O( ]. Q( ~$wordCount = count($wordlist);如果有单词列表模型,可以使用Eloquent来获取Collection,然后使用Collection的count例子:" C# S7 }0 [- b) ?/ E3 o2 N2 p
$wordlist = Wordlist::where('id','get();$wordCount = $wordlist->count();这里有/正在讨论让查询生成器返回一个集合:https$ [8 q, {& Q* [  W
:' ]) f3 O0 ]8 K/ Y
//github.com/laravel/framework/issues/10478
, R  @0 I4 t0 u9 P0 d. a但到目前为止,查询生成器总是返回一个数组。
$ `7 \3 y) t- g$ a编辑:以上链接,查询生成器现在返回集合(不是数组)。JP Foster最初尝试执行的操作将起作用:: L% b# ?! o( x" Q7 p
$wordlist = \DB::table('wordlist')->where('id','get();$wordCount = $wordlist->count();但是,正如Leon评论中指出,如果只需要计数,直接查询比获得整个集合和计数要快得多。换句话说,您可以执行以下操作:
. W5 o: E  q9 g9 K2 E9 f// Query builder$wordCount = \DB::table('wordlist')->where('id','count();// Eloquent$wordCount = Wordlist::where('id','count();;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则