0

I have a table named project which has a column named status, it takes 4 values : created, active, done, cancelled. I want to get a count object of each status in one query if it's possible :

[ "created" : 5, "active" : 34, "done" : 7, "cancelled" : 5 ] 
1
  • what's the type of the column? Commented Jun 12, 2020 at 11:03

2 Answers 2

1

You can get it in one query by doing this.

 $status = Project::select('status')->get(); $result = $status->groupBy('status')->map(fn ($v) => $v->count()); $status->count(); //total count, $result // this is the result you want. 
Sign up to request clarification or add additional context in comments.

Comments

0

you can do it via raw query

$rows = DB::select('SELECT count(*) as cnt, status_id FROM `projects` WHERE 1 group by status'); 

result:

array:5 [ 0 => { "cnt": 1 "status": 'status1' } 1 => { "cnt": 882 "status": 'status2' } ] 

to convert in your structure

$data = []; foreach ($row as $row) { $data[$row->status] = $row->cnt; } 

2 Comments

Is it possible to get the total count also?
in one query no I think, but you can do it inside loop

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.