【问题标题】:How to refactor Laravel Eloquent Query如何重构 Laravel Eloquent 查询
【发布时间】:2021-12-26 11:33:20
【问题描述】:

我有一个使用联接从 5 个表中检索数据的查询。虽然我得到了正确的结果,但速度很慢。

表格:

  • data_bundles
  • 供应商
  • ussd_strings
  • 产品用户
  • data_bundles_category

我该如何重构它?

此外,该设置不使用模型。

$data_bundle_transaction = DB::table('data_bundles')
    ->select('*','data_bundles.phone_number as data_bundles_phone_number')
    ->join('vendors','vendors.vendor_id','=','data_bundles.vendor_id')
    ->join('ussd_strings','data_bundles.product_id','=','ussd_strings.product_id')
    ->join('products','data_bundles.product_id','=','products.product_id')
    ->join('users','users.user_id','=','data_bundles.user_id')
    ->leftJoin('data_bundle_category', 'data_bundle_category.product_id', '=', 'data_bundles.product_id')
    ->where('data_bundles.status',0)
    ->where('data_bundles.network','like',  '%' . $request->network.'%')
    ->where('data_bundle_category.data_category', '=', $request->type)->first();

【问题讨论】:

  • 你想做什么重构?请分享您想要实现的目标。
  • 目前,查询需要很长时间才能完成。我需要一个能提高速度的。
  • 请检查 where 子句中的列是否有索引。 data_bundles 表中的状态、网络和 data_category 等列。
  • 这些列上没有索引
  • 请为我们提供每个相关表的生成 SQL 和 SHOW CREATE TABLE。

标签: mysql laravel database eloquent laravel-8


【解决方案1】:

您可以尝试使用多条件连接,这样您将连接更少的数据并且查询会更快

$data_bundle_transaction = DB::table('data_bundles')
->select('*','data_bundles.phone_number as data_bundles_phone_number')
->join('vendors','vendors.vendor_id','=','data_bundles.vendor_id')
->join('ussd_strings','data_bundles.product_id','=','ussd_strings.product_id')
->join('products','data_bundles.product_id','=','products.product_id')
->join('users','users.user_id','=','data_bundles.user_id')
->leftJoin('data_bundle_category', function() use ($request){
    $join->on('data_bundle_category.product_id', '=', 'data_bundles.product_id');
    $join->on('data_bundle_category.data_category', '=', $request->type);
})
->where('data_bundles.status',0)
->where('data_bundles.network','like',  '%' . $request->network.'%')
->first();

【讨论】:

    猜你喜欢
    • 2020-07-18
    • 1970-01-01
    • 2019-12-20
    • 1970-01-01
    • 2021-08-17
    • 1970-01-01
    • 2017-10-22
    • 1970-01-01
    • 2018-10-27
    相关资源
    最近更新 更多