I have an query that takes almost 3 minutes to give results. It pins one of the CPU cores at 100% the whole time.
I'm trying to figure out a way to get the same result without the expensive query. The results are correct, so I have no complaints about that.
App\Cladding.php(Model)
<?php
namespace App;
use App\BusinessParameters;
use Illuminate\Database\Eloquent\Model;
class Cladding extends Model
{
protected $fillable = [
'section_id',
'profile_id',
'width',
'length',
'guage_id',
'color_id',
'fastenertype_id',
'screw_spacing',
'orientation',
'rounding',
'vbar_coverage_per_day',
'vbar_num_of_men',
'insu_coverage_per_day',
'insu_num_of_men',
'subg_coverage_per_day',
'subg_num_of_men',
'mclosure',
'fclosure',
'custom_width',
];
...
public function getSequencingResultsAttribute()
{
// Count previous records including itself
$count = $this->section->claddings->where('id', '<=', $this->id)->count();
// Extract widths for those records
$SumOfWidths = $this->section->claddings->take($count)->sum('width');
// Count previous records not including itself
$count = $this->section->claddings->where('id', '<', $this->id)->count();
// Extract Results for those records
$PreviousResults = $this->section->claddings->take($count)->sum('SequencingResults');
// If rounding Down is selected
if ($this->rounding == 3) {
return floor($SumOfWidths / $this->SheetWidth - $PreviousResults);
}
// else round up
else {
return ceil($SumOfWidths / $this->SheetWidth - $PreviousResults);
}
}
...
the expensive part of this query is:
$PreviousResults = $this->section->claddings->take($count)->sum('SequencingResults');
If remove this line the calculation completes very quickly but of course it's incorrect.
Can anyone see the best way to trim this query down?