如何在不检索整个数据集的情况下按Laravel 4.2中的结果计算组数?

时间:2018-01-26 09:58:26

标签: php mysql laravel-4 eloquent laravel-eloquent

假设我有一张表customer_table,如下所示:

customer_name | country | city
--------------------------------------
John          | US      | New York
Paul          | US      | New York
Peter         | US      | Boston
Mary          | UK      | London
Lilian        | UK      | Boston

然后,在模型CustomerTable设置为指向此表的情况下,我有一个像这样的Eloquent查询:

$results = CustomerTable::groupBy('Country', 'City')->get();

我会得到一个如下所示的结果:(它作为一个对象返回,但为了更好看,我把它放在一个表中)

customer_name | country | city
--------------------------------------
John          | US      | New York
Peter         | US      | Boston
Mary          | UK      | London
Lilian        | UK      | Boston

然后我可以使用count($results)找到组合的数量。但是,我实际上只需要组合的数量。返回所有数据是浪费。 (即使我只返回一列,因为在实际情况下行数很大)。我试过了:

$results_count = CustomerTable::groupBy('Country', 'City')->count();

但这不起作用。它的方式是返回group by之前的行数。这是对旧项目的增强,所以我必须使用Laravel 4.2。如何使用Laravel 4.2中的Eloquent检索结果数而不检索整个数据集?

1 个答案:

答案 0 :(得分:0)

应该是结果的计数

$results = CustomerTable::groupBy('Country', 'City')->get();
$results_count = $results->count();

NB读你评论我建议你

select count(*) 
from my_table 
group by col1,col2 

返回每个col1,col2组合的非重复计数列表...而不是查询行数...

查询的行数相当于

     select count(*) from(
        select count(*) 
        from my_table 
        group by col1,col2
     )