如何重构 Laravel Eloquent 查询

How to refactor Laravel Eloquent Query

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

表格:

我该如何重构它?

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

$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();

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

$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();