[英]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
但出於不同的目的。
如何減少查詢?
你可以嘗試一下,
$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.