【问题标题】:eloquent laravel: How to get a row count from a ->get()雄辩的 laravel:如何从 ->get() 获取行数
【发布时间】:2016-02-14 01:55:45
【问题描述】:

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

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

我尝试了adding-&gt;count(),但没有成功。我试过做count($wordlist)。如果不需要第二个请求作为a-&gt;count() 方法,我不确定该怎么做。

【问题讨论】:

    标签: php sql laravel eloquent


    【解决方案1】:

    答案已更新

    count 是一个收集方法。查询生成器返回一个数组。因此,为了获得计数,您只需像通常使用数组一样计算它:

    $wordCount = count($wordlist);
    

    如果你有一个 wordlist 模型,那么你可以使用 Eloquent 获取一个 Collection,然后使用 Collection 的 count 方法。示例:

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

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

    但是到目前为止,查询构建器始终返回一个数组。

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

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

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

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

    【讨论】:

    • 使用 where 子句直接访问 count() 比返回整个集合要快。例如,如果这是对整个用户表的计数,则可能仅返回 1m 个结果来计数它们,这将占用大量资源。
    • 对我来说,即使有更多结果,查询生成器也会给出计数 1。使用相同的 queryBuilder 我返回其他结果。
    • 它与 db:table 一样工作
    【解决方案2】:

    直接获取行数

    使用 Eloquent

     //Useing Eloquent
     $count = Model::count();    
    
     //example            
     $count1 = Wordlist::count();
    

    使用查询生成器

     //Using query builder
     $count = \DB::table('table_name')->count();
    
     //example
     $count2 = \DB::table('wordlist')->where('id', '<=', $correctedComparisons)->count();
    

    【讨论】:

    • 这应该在顶部
    • 雄辩的更优雅
    【解决方案3】:

    最好用 laravel 的 count 方法来访问计数

    $count = Model::where('status','=','1')->count();
    

    $count = Model::count();
    

    【讨论】:

      【解决方案4】:

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

      控制器中的代码

      $posts = Post::all();
      return view('post', compact('posts'));
      

      刀片文件中的代码。

      {{ $posts->count() }}
      

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-15
        • 2020-12-02
        • 2016-03-09
        • 2016-03-22
        • 1970-01-01
        • 2019-07-16
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多