Hi. An appended accessor makes very slow the response (about 30 seconds.).. I'll try to explain with codes below..
My problematic eloquent model is :
$machines = Machine::where($condition)->with(['jobs' => function ($query) { $query->orderBy('queue', 'asc');
},'jobs.part.image', 'jobs.project.customer', 'jobs.state.stateLang', 'operator.image'])->get();
eager loaded project relation in my model jobs.project.customer has appended accesssor as follow:
Project Model:
protected $appends = ['stats'];
public function getStatsAttribute()
{
return (new ProjectController)->stats($this->id);
}
I use that attribute to attach project progress for every project record. Actually I don't need that in my problematic collection but it gets. And my function in which I calculated stats is as follow:
public function stats($id)
{
$totalJobs = 0;
$totalCompletedJobs = Job::where('project_id', $id)->where('state_id', '!=', 4)->sum('completed');
foreach (Job::where('project_id', $id)->where('state_id', '!=', 4)->cursor() as $job) {
$part = Part::find($job->part_id);
$totalJobs = $totalJobs + $part->quantity;
}
return ['totalJobs' => $totalJobs, 'totalCompletedJobs' => (int)$totalCompletedJobs];
}
Is that method wrong to get stats in that appended attribute way? Besides, actually I don't need project stats in that $machine collection, when getting project.customer relation it takes that accessor also. How Can I do that in correct way? Can I cancel appended attribute for once for any query?
Edit: Additionally, this works very fast (around 300ms) on localhost. On shared server it takes about 30 seconds. Is that difference in possible range?