Update: Solved, problem was not eloquent, it's quite efficient in using multiple scopes across multiple models. I had an output in my view which would query for each resident the occupations, room and floor. This led to over 2600 queries for ~200 residents and was the reason for my performance drop. I now use eager loading to get all occupations and rooms with the first query by adding ->with(['occupation.room'])
.
I have a model which consists of residents who live in rooms. Those rooms are rented out for a certain period of time which is why we have a table occupations. This table determines which resident lives where. Here's a visualisation:
My problem is that Eloquent has no efficient way to determine all residents living house X or all residents on floor Y (see floor model for house attr).
I am using query scopes on Room:
public function scopeHouse($query, $house) {
return $query->whereHas('floor', function($q) use($house) {
$q->where('house', $house);
});
}
On Occupation:
public function scopeHouse($query, $house) {
return $query->whereHas('room', function($q) use($house) {
$q->house($house);
});
}
And Resident:
public function scopeHouse($query, $house) {
return $query->whereHas('occupation', function($q) use($house) {
$q->house($house);
});
}
Which is obviously not very efficient. I could just query all occupations and then query rooms and residents individually but that would destroy eloquents nice fluent api.
Any suggestions?