I am working on this query: (I wish I could pass this same query using eloquent and return a JSON as response.)
public function getChart(Request $request)
{
$_orders = DB::table('users')
->join('orders','orders.user_id','=','users.id')
->join('model_has_roles', 'users.id', '=', 'model_has_roles.model_id')
->select('users.id','users.name', DB::raw('COUNT(orders.id) as orders_by_user'), 'model_has_roles.role_id as rol')
->where('model_has_roles.role_id', '2');
$_orders->groupBy('orders.user_id', 'users.id', 'users.name', 'model_has_roles.role_id');
$orders=$_orders->get();
return ['orders' => $orders];
}
This query is already resolved and returns me as a result: the name of the operator who was assigned a work order and the number of work orders in finished state that that operator has.
for this, relate the users table and the orders table.
{
"orders": [
{
"id": 4,
"name": "Luis",
"orders_by_user": 2,
"rol": 2
},
{
"id": 6,
"name": "Jose",
"orders_by_user": 1,
"rol": 2
},
{
"id": 7,
"name": "Miguel",
"orders_by_user": 1,
"rol": 2
}
]
}
If you look at my query response, my array is called orders inside orders I get what I need:
"orders": [
{
"id": 4,
"name": "Luis",
"orders_by_user": 2,
"rol": 2
},
As I mentioned earlier, I wish I could pass this same query using eloquent and return a JSON in response.
How can I customize this JSON response?
It would be something like this: separate name in one array and orders_by_user in another array
example of what I want to achieve
"users": [
{
"name": "Luis"
}
]
"orders": [
{
"orders_by_user": 2
}
]
I need your help