i building a laravel nova admin panel and using custom metrics to do some calculations however it's taking a loooot of time ( 10 minutes ) i doon't understand why
i used :
$model->get()->sum('attribute')
and
foreach
@aureliee123 You should save the total against each order rather than recalculating it every time. You can then ask the database to sum the order total. If your total() function is pulling records from other tables, it might work fine when reviewing one order, but when totalling multiple orders you will have a horrible n+1 issue.
In such a scenario, your total() should run at the point of placing the order or when the delivery is confirmed, then the calculated amount is saved into the order like what Snapey suggested.
So you will need to create a total field in your orders table and it should start as NULL by default, this way, you won't need the setTotalAttribute(...).
Attributes should not contain queries, it will likely make the app very slow over time, I only use attributes to reformat data or do simple maths on fields that are already loaded.
Attributes also can't be utilized by MySQL. These are all design considerations the architect will have to factor in.