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.'%');});
目前我使用子查詢方法獲取結果,但我認爲它沒有優化,因爲多次執行相同的搜索查詢。
請建議。
謝謝。
問題在於通配符,您無法優化使用'LIKE'%text%''的查詢,因爲它無法使用索引,所以您需要刪除第一個通配符爲了加快這個查詢。 – FMashiro
考慮使用'FULLTEXT'索引。 –