簡體   English   中英

減少類似的查詢

[英]Reducing the similar like queries

我有這四個類似的查詢:

        $products=Product::orderBy('views','desc')->with('category')->get();  //----1
        $mostviews=Product::orderBy('views','desc')->limit(10)->get();        //----2
        $show=Product::orderBy('views','desc')->with('category')
                                                    ->with('user')
                                                    ->with('productbrand.brand')                                        
                                                    ->first();                      //----3

        $shows=Product::orderBy('views','desc')->limit(20)
                                                     ->with('category')
                                                     ->with('user')
                                                     ->with('productbrand.brand')                                        
                                                     ->get();                       //----4

但出於不同的目的。

  1. 獲得所有類別的產品。
  2. 獲得10個產品
  3. 獲得一個包含類別,用戶和品牌的產品
  4. 獲得20種產品類別,用戶和品牌

如何減少查詢?

你可以嘗試一下,

$po= Product::orderBy('views','desc');
$products=$po->with('category')->get();  //---1
$mostviews=$po->limit(10)->get();        //---2
$shows=$po->limit(20)
          ->with('category')
          ->with('user')
          ->with('productbrand.brand')                 
          ->get(); 

$show=$shows[0];                      //----3

在你的控制器中

$products = Product::orderBy('views','desc')->with(['category','user','productbrand.brand'])->get();

return view('product.list',compact('products'));

在你的視圖中

$all = $products;
$mostViews = $products->take(10);
$show = $products->first();
$shows=  $products->take(20);

您不需要創建所有這些變量。 這樣做:

$products = Product::orderBy('views','desc')
                   ->with('category', 'user', 'productbrand.brand')
                   ->get();

獲得數據后,使用此變量。 但是如果您在DB中有產品描述和/或規格,我還建議您不要使用take()方法。 因為如果你這樣做,它可以輕松占用所有內存。 事情就是每個take()都會創建新的集合

您可以使用$products而無需創建新的集合或變量:

// Show:
{{ $products->first()->id }}

// Most views:
@foreach ($products as $product)
    @if ($loop->iteration > 10)
        @break
    @endif

    {{ $product->something }}
@endforeach

// Shows:
@foreach ($products as $product)
    @if ($loop->iteration > 20)
        @break
    @endif

    {{ $product->something }}
@endforeach

暫無
暫無

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

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