选择不同的值计数 laravel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22131609/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:07:33  来源:igfitidea点击:

Select distinct value count laravel

sqllaravel

提问by ultimate

I have an orders table where there is a status column.

我有一个订单表,其中有一个状态列。

I am trying to get the count of each status like this :

我正在尝试像这样计算每个状态的数量:

$pending = Order::where('status','=','pending')->count();
$active = Order::where('status','=','active')->count();

But this is not efficient as am having to make one call for each status type.

但这效率不高,因为我必须为每种状态类型拨打一个电话。

How can I reduce number of queries ?

如何减少查询次数?

回答by Alexandr Pisarenko

To make an SQL request:

要发出 SQL 请求:

SELECT count(DISTINCT `status_id`) FROM `dbname`.orders WHERE `user_id` = '2';

In Laravel you can try the following:

在 Laravel 中,您可以尝试以下操作:

$user->orders()->distinct()->count(["status_id"]);

回答by TonyArra

You could try

你可以试试

$orders = Order::select(DB::raw('count(*) as order_count, status'))
  ->groupBy('status')
  ->get();

回答by priti

here is the way you write ->

这是你写的方式 - >

$users= DB::table('table_name')->distinct()->get(['column_name']);
$users_count = $users->count();