I have the following DB::select statement:
JavaScript
x
DB::select("SELECT user_id, COUNT(*) AS orders_count FROM order_book as ob WHERE session_id='".$session_id."' GROUP BY user_id");
Which its result will be something like:
JavaScript
[{
"user_id": 2,
"orders_count": 6
},
{
"user_id": 340,
"orders_count": 83
},
{
"user_id": 341,
"orders_count": 88
}]
what is the equivalent statement using the Eloquent model?
This is what I have so far:
JavaScript
Order::whereSession_id($session_id)->select('user_id','Count(*)')->groupBy('user••_id')->get();
Advertisement
Answer
You can use this:
JavaScript
Order::select('user_id', DB::raw('count(*) as orders_count'))
->where('session_id', $session_id)
->groupBy('user••_id')
->get();
You need to use DB::raw
when using count
in your query’s select, because otherwise it will get quoted by PDO.