I am trying to achieve the following with Eloquent :
I want to query my DB, count the amount of rows where status = 'waiting' and 'inprogress', but I'm running into the following problem. If I run the get() and then try to count, I get told I can't on a non-object. If I try to run the get() after, I get this error : Undefined property: Laravel\Database\Query::$source
.
Here are my two attempts :
//get() before
$devs = Dev::todo($user_id)->get(array('id', 'type', 'title', 'source', 'priority', 'status', 'for_user', 'priority', 'desc', 'created_at'));
$devs->num_waiting = $devs->where('status', '=', 'waiting')->count();
$devs->num_inprogress = $devs->where('status', '=', 'inprogress')->count();
//get() after
$devs = Dev::todo($user_id);
$devs->num_waiting = $devs->where('status', '=', 'waiting')->count();
$devs->num_inprogress = $devs->where('status', '=', 'inprogress')->count();
$devs->get(array('id', 'type', 'title', 'source', 'priority', 'status', 'for_user', 'priority', 'desc', 'created_at'));
My todo function :
public static function todo($user_id) {
$todo = Dev::where('for_user', '=', $user_id)
->where(function($query) {
$query->where('status', '=', 'active')
->or_where('status', '=', 'inprogress')
->or_where('status', '=', 'waiting');
})
->order_by('priority', 'asc')
->order_by('created_at', 'desc');
return $todo;
}
How can I run get() after counting the data I need to count, why is this happening, and is there a better way to do this?
The problem here is
get()
returns aCollection
which does not contain awhere()
method so you need to dowhere()
beforeget()
. Fortunately, yourget()
seems to be taking place of aselect()
so you should use that instead.Try this...
Now you should be able to run your counts off it, but doing it twice isn't going to work because the second count time will be counting
waiting
andinprogress
. We can create another object for finding the other count, but it's also not very good on performance because you are running basically the same query 3 times. Two for counts, and one for returning the actual collection. What I would do is get your collection, and count it using php as you iterate over it.This code is untested though because I'm not sure what you are doing with your
todo()
function.