2017-06-16 30 views
-1

我需要你們的幫助,因爲我想在較少,可以優化這些查詢...Laravel雄辯指望其中()5個關係深

我想提醒這是在計數:
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(); 

你能幫我嗎?謝謝!我能想到的快速

回答

0

一種優化是這樣的:

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

而不是獲取整個行只得到count.if有大量沒有警報和行動,你將有一個良好的性能提升。

+0

謝謝你這部分:) – HapLifeMan

+0

你的歡迎:) –