【问题标题】:Laravel 5.4 Eloquent Query OptimizationLaravel 5.4 Eloquent 查询优化
【发布时间】:2017-10-07 13:12:16
【问题描述】:

我想优化产品列表的 Laravel 查询。我需要显示产品列表和品牌。以下是代码:

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

对于搜索返回的产品,我还需要单独列出所有品牌。

方法一:

获取数组中的所有品牌 ID

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

问题是由于产品分页,这只会获得 10 条记录的品牌

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

方法二(子查询):

$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%'的查询,因为它不能使用索引,所以你需要删除第一个通配符才能加快查询速度。
  • 考虑使用FULLTEXT 索引。

标签: php mysql laravel optimization eloquera


【解决方案1】:

分页在限制和偏移的基础上工作,因此您必须进行第二次查询才能获得整个品牌。在获取产品品牌的方法 1 中,您可以如下所示更改查询,这样您就不需要单独获取品牌 ID。

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

【讨论】:

    猜你喜欢
    • 2018-05-27
    • 2021-07-22
    • 2020-09-24
    • 2018-02-27
    • 1970-01-01
    • 2020-12-17
    • 2019-06-28
    • 2018-10-11
    • 2017-11-14
    相关资源
    最近更新 更多