简体   繁体   English

如何使用 eloquent 从查询中返回 JSON 响应?

[英]How to return JSON response from a query with eloquent?

I am working on this query: (I wish I could pass this same query using eloquent and return a JSON as response.)我正在处理这个查询:(我希望我可以使用 eloquent 传递相同的查询并返回一个 JSON 作为响应。)

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 inside orders 我得到了我需要的东西:

"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.正如我之前提到的,我希望我可以使用 eloquent 传递相同的查询并返回一个 JSON 作为响应。

How can I customize this JSON response?如何自定义此 JSON 响应? It would be something like this: separate name in one array and orders_by_user in another array它会是这样的:一个数组中的单独名称和另一个数组中的 orders_by_user

example of what I want to achieve我想要实现的目标的例子

"users": [
{

"name": "Luis"
}
]
"orders": [
{

"orders_by_user": 2

}
]

I need your help我需要你的帮助

you can return json response like this你可以像这样返回json响应

return response()->json(['name' => 'Abigail', 'state' => 'CA'])

read documentation here在这里阅读文档

https://laravel.com/docs/7.x/responses#json-responses https://laravel.com/docs/7.x/responses#json-responses

Note explaining relations to @Rodrigo Ruiz注意解释与@Rodrigo Ruiz 的关系

in user model has your relation like this在用户模型中有你这样的关系

class User extends Model
{
    public function Orders()
    {
        return $this->hasMany(App\Order::class);
    }
}

Order Model订单模型

class Order extends Model
{
    public function user()
    {
        return $this->belongsTo(App\User::class);
    }
}

$user = User::first();

get all orders of user获取用户的所有订单

$orders = $user->orders()->get();

get first order拿到第一单

$order = $user->orders()->first();

if you call relation each time it will execute a query on each call.如果您每次调用关系,它将在每次调用时执行查询。

Optimize call of relations it will load all relations just in 1 query.优化关系调用,它将在 1 个查询中加载所有关系。

$user = User::with('orders')->get();

$order = $user->orders->first();
  • List item项目清单

@umefarooq is right, I always follow his steps and sometimes if I don't want it to return all the values of that particular model, I return the result through Laravel API Resource . @umefarooq是对的,我总是遵循他的步骤,有时如果我不希望它返回该特定模型的所有值,我会通过Laravel API Resource返回结果。 This gives you the flexibility to determine which fields you will like to return from the eloquent query.这使您可以灵活地确定要从 eloquent 查询返回哪些字段。

In your controller, rather than use it like在您的控制器中,而不是像这样使用它

return response()->json($order);

I use it like this我像这样使用它

 return OrderResource::collection($orders); 

You can customize this query to any style you want as long as you know how to pass all required parameters into the collection.只要您知道如何将所有必需的参数传递到集合中,您就可以将此查询自定义为您想要的任何样式。 So if you want to fetch just the basic information about a user and order:因此,如果您只想获取有关用户和订单的基本信息:

class OrderResource extends JsonResource
return [
           'user'=>[
                'id' => $this->id,
                'name' => $this->name,
                  ],
            'orders'=>[
                'order_id' => $this->order->order_id,
                'order_rol' =>  $this->rol
            ]
        ];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM