Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select distinct value count laravel

Tags:

sql

laravel

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 ?

like image 682
ultimate Avatar asked Mar 02 '14 18:03

ultimate


People also ask

How to get distinct values in Laravel query?

$users = User::select('name')->groupBy('name')->get()->toArray() ; groupBy is actually fetching the distinct values, in fact the groupBy will categorize the same values, so that we can use aggregate functions on them.

What is distinct() in Laravel?

In Laravel, the distinct() method is used to fetch distinct records from the database, it is also part of Laravel query builder, which means it can be chained to other query builder methods as well. The typical usage of this method is to find how many users made comments on a post.


3 Answers

To make an SQL request:

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

In Laravel you can try the following:

$user->orders()->distinct()->count(["status_id"]);
like image 165
Alexandr Pisarenko Avatar answered Sep 20 '22 18:09

Alexandr Pisarenko


You could try

$orders = Order::select(DB::raw('count(*) as order_count, status'))
  ->groupBy('status')
  ->get();
like image 23
TonyArra Avatar answered Sep 18 '22 18:09

TonyArra


here is the way you write ->

$users= DB::table('table_name')->distinct()->get(['column_name']);
$users_count = $users->count();
like image 41
priti Avatar answered Sep 18 '22 18:09

priti