Skip to content

Commit baf48f9

Browse files
authored
Merge pull request #62 from kirschbaum-development/performance/improve-query
Improve chart fetching performance
2 parents de53717 + 85ac5a9 commit baf48f9

File tree

1 file changed

+25
-15
lines changed

1 file changed

+25
-15
lines changed

src/Traits/HasChart.php

Lines changed: 25 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -77,22 +77,32 @@ public function setNovaChartjsMetricValueAttribute($value): void
7777
*/
7878
public static function getNovaChartjsComparisonData($chartName = 'default'): array
7979
{
80-
return static::with('novaChartjsMetricValue')
80+
$resources = static::query()
8181
->has('novaChartjsMetricValue')
82-
->get()
83-
->map(function ($chartData) use ($chartName) {
84-
$chartData->setAttribute(
85-
'novaChartjsComparisonData',
86-
optional($chartData->novaChartjsMetricValue()->where('chart_name', $chartName)->first())->metric_values
87-
);
88-
89-
return $chartData;
90-
})
91-
->reject(function ($chartData) {
92-
return empty($chartData->novaChartjsComparisonData);
93-
})
94-
->values()
95-
->toArray();
82+
->get();
83+
84+
$charts = NovaChartjsMetricValue::query()
85+
->select('chartable_id', 'metric_values')
86+
->whereIn('chartable_id', $resources->pluck('id'))
87+
->where('chartable_type', static::class)
88+
->where('chart_name', $chartName)
89+
->toBase()
90+
->get();
91+
92+
return $resources->map(function ($resource) use ($charts) {
93+
$data = optional($charts->first(function ($chart) use ($resource) {
94+
return $chart->chartable_id === $resource->id;
95+
}))->metric_values;
96+
97+
$resource->setAttribute(
98+
'novaChartjsComparisonData',
99+
$data ? json_decode($data, true) : null,
100+
);
101+
102+
return $resource;
103+
})
104+
->values()
105+
->toArray();
96106
}
97107

98108
/**

0 commit comments

Comments
 (0)