I have the following DB::select statement:
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:
[{ "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:
Order::whereSession_id($session_id)->select('user_id','Count(*)')->groupBy('user_id')->get();
Advertisement
Answer
You can use this:
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.