php - Eager load extra model attributes -
i using eloquent laravel.
the case: i'm building api there possibility include
relations resource. example /api/teams?include=users
add user
model every team
. logic includes relationship i'm using fractal. need have logic determines relationship has included, can create optimized query it.
problem: when want render collection of team
related user
models. can eager-load models fine. problems comes when have custom attributes on user
model. these cause n+1 query problem because every eager-loaded team, because query custom attributes executed every model.
example code:
// team model custom attribute class team extends model { protected $appends = ['is_member']; public function getismemberattribute() { $loggeduser = auth::currentuser(); $result = db::table('team_user') ->where('team_id', $this-id) ->where('user_id', $loggeduser->id) ->get(); return !is_null($result); } } // controller code $team = team::findorfail($teamid); // return user models belong team. // problem execute query inside getismemberattribute() every user model. dd($team->users);
is there pattern solve issue?
you iterate through user models , see if 1 of them matches logged in user. it's more efficient looking in database.
class team extends model { protected $appends = ['is_member']; public function getismemberattribute() { $loggeduser = auth::currentuser(); foreach ($this->users $user) { if ($user->id == $loggeduser->id) { return true; } } return false; } }
Comments
Post a Comment