php - Laravel 5.4 custom join (raw sql) mapped to an Eloquent Model -
can tell me how can map result of join made raw sql or query builder eloquent model ?
teams has many users has many students has many projects
i'm doing join projects of team through sub relations
example :
$projects = project::join('students', 'students.id', '=', 'projects.student_id') ->join('users', 'users.id', '=', 'students.user_id') ->join('teams', 'teams.id', '=', 'users.team_id') ->select('projects.*', 'students.*', 'users.*', 'teams.*') ->get();
now, how can result here mapped collection of "project" model having sub relations mapped respective model
- student
- user
- team
you don't need use joins. use eloquent's eager loading instead.
provided have relations defined correctly in models, following should trick:
$projects = project::with('student.user.team')->get(); foreach($projects $project) { $student = $project->student; //student model $user = $student->user; // user model $team = $user->team; // team model }
update: if want fetch projects given team following:
$projects = project::with('student.user.team')->wherehas('student.user.team', function($query) use ($teamid) { $query->whereid($teamid); })->get();
Comments
Post a Comment