亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用 Eloquent 重構此代碼以緩解 N+1 查詢問題?

如何使用 Eloquent 重構此代碼以緩解 N+1 查詢問題?

PHP
慕容森 2024-01-19 16:45:42
我想了解在這種特殊情況下,是否有一種有效的方法可以使用 Eloquent 來緩解 N+1 查詢問題。背景是我目前正在使用 Laravel 8 構建一個 API。概括就本題而言,示例是Store-> has much -> Orders-> Many-to-many -> Products,即:一個商店有很多訂單,一個訂單有很多產品,但一個產品可以屬于很多不同的商店。有一個product_orders數據透視表,它還跟蹤一些附加值,例如unit_price等quantity。我的目標是創建一個 API 端點,其中列出了商店的所有訂單以及該特定訂單上的產品。{    "data": [        {            "id": "6531a4d4-b066-4673-ad59-8b4a49c0d675",            "object": "order",            "comments": "Sequi perspiciatis quasi dolorum rerum. Rem dolore nihil sint magnam totam explicabo. Non officia est ut inventore modi.",            "order_items": [                {                    "product_id": "3c6400f5-fde9-47cb-ad05-ef164e00583e",                    "product_name": "omnis inventore",                    "unit_price": "17.15",                    "quantity": 8                },                {                    "product_id": "c208c8dd-df71-4331-909d-0615ec763555",                    "product_name": "accusantium omnis",                    "unit_price": "81.88",                    "quantity": 3                },                {                    "product_id": "05129518-882b-4558-b68f-df06c804a6d3",                    "product_name": "voluptatem vitae",                    "unit_price": "52.58",                    "quantity": 4                },            ],            "supplier_invoice_no": ABC1234,        }    ],    }}對于此任務,我利用 Eloquent API 資源,因此我的代碼如下:路線/api.phpRoute::apiResource('/stores/{store}/orders', 'Api\Stores\StoreOrderController');StoreOrderController.php我正在Store使用路由模型綁定檢索模型。public function index(Store $store)    {        return StoreOrdersResource::collection($store->orders);    }商店訂單資源.php這個 API 資源將 JSON 響應過濾為僅相關數據,我相信這就是我的問題所在。對于Order通過此的每一個StoreOrdersResource,我都會檢索$this->productsaka $order->products,因此會進行重復的查詢,為商店的每一個訂單查詢訂單的產品。
查看完整描述

1 回答

?
鳳凰求蠱

TA貢獻1825條經驗 獲得超4個贊

為了避免額外的查詢,您可以在控制器中加載關系。就像是


// Models/Order.php

public function items()

{

    return $this->belongsToMany(Product::class)

                ->withPivot('unit_price', 'quantity');

}



// StoreOrderController.php

public function index(Store $store)

{

    $store->load('orders.items');


    return StoreOrdersResource::collection($store->orders);

}


// StoreOrdersResource.php

public function toArray($request)

{

    return [

        // ...

        'order_items' => $this->items,

    ];

}


查看完整回答
反對 回復 2024-01-19
  • 1 回答
  • 0 關注
  • 149 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號