2017-05-09 146 views
1

我想爲產品列表優化Laravel查詢。我需要展示產品列表以及品牌。以下是代碼:Laravel 5.4雄辯查詢優化

$searchTerm = 'Coffee'; 
$productListing = Product::where('title', 'like', '%'.$searchTerm.'%')->paginate(10); 

我還需要爲各品牌通過搜索返回的產品單獨的列表。

方法1:

獲取在陣列中的所有品牌IDS

$productBrandsArray = $productListing->pluck('brand_id')->toArray(); 

問題是這樣只會讓品牌,因爲產品的10條記錄分頁

$productBrands = Brand::whereIn('brand_id', $productBrandsArray); 

方法2(子查詢):

$productBrands = Brand::whereIn('brand_id', function ($query) use($searchTerm) { 
$query->select('brand_id') 
->from(with(new Product())->getTable()) 
->where(Product::getTableName().'.title', 'like', '%'.$searchTerm.'%');}); 

目前我使用子查詢方法獲取結果,但我認爲它沒有優化,因爲多次執行相同的搜索查詢。

請建議。

謝謝。

+0

問題在於通配符,您無法優化使用'LIKE'%text%''的查詢,因爲它無法使用索引,所以您需要刪除第一個通配符爲了加快這個查詢。 – FMashiro

+0

考慮使用'FULLTEXT'索引。 –

回答

1

分頁正在限制和抵消的基礎上工作,所以你必須進行第二次查詢才能獲得整個品牌。在獲取產品品牌的方法1中,您可以更改下面給出的查詢,因此您不需要單獨獲取品牌ID。

$productBrands = Brand::where('products.title', 'like', '%' . $searchTerm . '%') 
       ->join("products", "brands.brand_id", "=", "products.brand_id") 
       ->get();