簡體   English   中英

Laravel 4.2 n + 1沒有急切加載

[英]Laravel 4.2 n+1 without eager loading

我有一張產品表

products
------------------------------------------------
id  product_code    purchase_type   quantity
1   106             new             1
2   107             renew           3

和產品的價格表

price_list
----------------------------------------------------------------------
id  product_code    purchase_type   minimum     maximum     unit_price
1   106             new             1           25          20
2   106             new             26          50          16
3   106             new             51          100         14

當我在頁面上顯示產品時,我需要使用公式顯示價格

getPrice(product_code, purchase_type, quantity) for every product

運用

foreach(Product::all() as $product){
    {{ $product->product_code }}
    {{ $product->purchase_type }}
    {{ $product->quantity }}
    {{ PriceList::getPrice($product->product_code, $product->purchase_type, $product->quantity) }} - this one is the n+1 problem
}

PriceList :: getPrice()類似於:

public static function getPrice($productCode, $purchaseType, $quantity){
    return PriceList::where('product_code', $productCode)
        ->where('purchase_type', $purchaseType)
        ->where('minimum', '>=', $quantity)
        ->where('maximum', '<=', $quantity)
        ->get()->first()->unit_price;
}

我似乎找不到更有效的方法。 當我展示超過1000種產品時,它變得非常慢。 我似乎找不到使用急切加載的方法。

從內部循環調用模型來獲取數據不是一個好主意。

請遵循以下方式,而不是這樣做。

您應該定義Product和PriceList表之間的關系

在Model Product.php中

 public function price_list(){
    return $this->hasMany('PriceList','product_code');
 }

在Model PriceList.php中

 public function product(){
    return $this->belongsTo('Product','product_code');
 }

在控制器文件中

 $products = Product::with('price_list')->get();
 return View::make('your_view')->with('products', $products);

在視圖文件中 (文件必須具有擴展名.blade.php才能使用以下語法)

 @foreach($products as $product)
  {{ $product }}
 @endforeach

注意 : - 在控制器中打印$ products以檢查結果。

我找到了一種使用mysql的方法,

SELECT
   `products`.`id` AS `product_id`,
   `products`.`product_code` AS `product_product_code`,
   `products`.`purchase_type` AS `product_purchase_type`,
   `products`.`quantity` AS `product_quantity`,
   `price_list`.`product_code` AS `price_list_product_code`,
   `price_list`.`purchase_type` AS `price_list_purchase_type`,
   `price_list`.`minimum` AS `price_list_minimum`,
   `price_list`.`maximum` AS `price_list_maximum`,
   `price_list`.`unit_price` AS `price_list_unit_price`
FROM
   `products`
LEFT JOIN `price_list` ON `products`.`product_code` = `price_list`.`product_code`
AND `products`.`purchase_type` = price_list.purchase_type
AND `products`.`quantity` >= price_list.minimum
AND `products`.`quantity` <= price_list.maximum
ORDER BY
   `products`.`id` ASC

http://sqlfiddle.com/#!9/5d6ac/2

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM