Can somebody tell me how i can map the result of a Join made with RAW SQL or the Query Builder to an Eloquent Model ?
Teams has many Users who has Many Students who has many Projects
I'm doing a join to get all the projects of a team through the 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 i get the result here to be mapped to a Collection of "Project" Model having the sub relations mapped their respective Model
You don't need to use joins. Use Eloquent's eager loading instead.
Provided you have relations defined correctly in your models, the following should do the trick:
$projects = Project::with('student.user.team')->get();
foreach($projects as $project) {
$student = $project->student; //Student model
$user = $student->user; // User model
$team = $user->team; // Team model
}
UPDATE: If you want to fetch projects for given team do the following:
$projects = Project::with('student.user.team')->whereHas('student.user.team', function($query) use ($teamId) {
$query->whereId($teamId);
})->get();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.