user2901304
user2901304

Reputation: 713

Chain eager loading

I have three tables in my database

  1. Projects
  2. Milestones
  3. Tasks

A project can have many milestones and a milestone can have many tasks.

Is there a way using eloquent model to create a query to grab all the milestones with all the tasks associated to that milestone in 1 resultset. I've managed to get all the milestones that belong to my project.

This is my ProjectsController:

public function getProject($id)
{       
    $project = Project::findOrFail($id)->with('milestones');
    return $project;
}

I have all the relationships build in the models:

Project Model:

public function milestones(){
    return $this->hasMany('Milestone');
}

Milestone Model:

public function project(){
    return $this->belongsTo('Project');
}

public function tasks(){
    return $this->hasMany('Task');
}

Task Model:

public function milestone(){
    return $this->belongsTo('Milestone');
}

Upvotes: 0

Views: 157

Answers (1)

peterm
peterm

Reputation: 92785

You can specify multiple (nested too) relationships while eager loading

$project = Project::with(['milestones', 'milestones.tasks'])->findOrFail($id);

Let's tinker it:

[1] > $id = 1;
// 1
[2] > $project = Project::with(['milestones', 'milestones.tasks'])->findOrFail($id)->toArray();
// array(
//   'id' => 1,
//   'name' => 'Project1',
//   'created_at' => '2014-07-12 02:57:55',
//   'updated_at' => '2014-07-12 02:57:55',
//   'milestones' => array(
//     0 => array(
//       'id' => 1,
//       'name' => 'Milestone11',
//       'project_id' => 1,
//       'created_at' => '2014-07-12 02:58:12',
//       'updated_at' => '2014-07-12 02:58:12',
//       'tasks' => array(
//         0 => array(
//           'id' => 1,
//           'name' => 'Task111',
//           'milestone_id' => 1,
//           'created_at' => '2014-07-12 02:58:53',
//           'updated_at' => '2014-07-12 02:58:53'
//         ),
//         1 => array(
//           'id' => 2,
//           'name' => 'Task112',
//           'milestone_id' => 1,
//           'created_at' => '2014-07-12 02:59:02',
//           'updated_at' => '2014-07-12 02:59:02'
//         )
//       )
//     ),
//     1 => array(
//       'id' => 2,
//       'name' => 'Milestone12',
//       'project_id' => 1,
//       'created_at' => '2014-07-12 02:58:22',
//       'updated_at' => '2014-07-12 02:58:22',
//       'tasks' => array(
//         0 => array(
//           'id' => 3,
//           'name' => 'Task121',
//           'milestone_id' => 2,
//           'created_at' => '2014-07-12 02:59:12',
//           'updated_at' => '2014-07-12 02:59:12'
//         )
//       )
//     )
//   )
// )

Upvotes: 2

Related Questions