【问题标题】:Laravel Eloquent count on whereIn() 5 relations deepLaravel Eloquent 依靠 whereIn() 5 深度关系
【发布时间】:2017-06-16 11:00:41
【问题描述】:

我需要您的帮助,因为我想尽可能优化这些查询...

我想获取以下位置的警报计数:
companies -> sites -> interventions -> purchases -> alerts

我想获取以下操作的计数:
contractors -> actions
companies -> actions

我做了以下但每个页面上的 7 个请求并不是很好:/

$companies = Company::where('id', '=', Auth::user()->userable_id)->orWhere('company_id', '=', Auth::user()->userable_id)->pluck('id')->toArray();
$contractors = Contractor::where('id', '=', Auth::user()->userable_id)->orWhere('company_id', '=', Auth::user()->userable_id)->pluck('id')->toArray();

$cp = array_merge($companies, $contractors);

$sites = Site::whereIn('company_id', $companies)->pluck('id')->toArray();
$interventions = Intervention::whereIn('site_id', $sites)->pluck('id')->toArray();
$purchases = Purchase::whereIn('intervention_id', $interventions)->pluck('id')->toArray();
$bubblecounts['alerts'] = Alerts::whereIn('purchase_id', $purchases)->where('status', 0)->whereDate('alert_date', '!=', '0000-00-00 00:00:00')->count();
$bubblecounts['actions'] = Action::whereIn('actionable_id', $cp)->where([['status', 0], ['alert_date', '!=', null]])->count();

你能帮帮我吗?谢谢!

【问题讨论】:

    标签: mysql laravel eloquent


    【解决方案1】:

    我能很快想到的一个优化是这样的:

    $alerts = Alerts::whereIn('purchase_id', $purchases)->where('status', 0)->whereDate('alert_date', '!=', '0000-00-00 00:00:00')->count();
    $actions = Action::whereIn('actionable_id', $cp)->where([['status', 0], ['alert_date', '!=', null]])->count();
    
    $bubblecounts['alerts'] = $alerts;
    $bubblecounts['actions'] = $actions;
    

    而不是获取整个行,它只获取计数。如果没有大量警报和操作,您将获得良好的性能提升。

    【讨论】:

      猜你喜欢
      • 2020-03-12
      • 2021-05-09
      • 2017-04-01
      • 2015-04-16
      • 2019-11-12
      • 2021-12-06
      • 2021-01-14
      • 2016-08-16
      • 2020-08-01
      相关资源
      最近更新 更多