连锁急切加载

时间:2014-07-12 02:16:55

标签: php laravel laravel-4

我的数据库中有三个表

  1. 项目
  2. 里程碑
  3. 任务
  4. 项目可以有很多里程碑,里程碑可以有很多任务。

    有没有办法使用eloquent模型创建一个查询来获取所有里程碑,其中包含与1个结果集中的里程碑相关的所有任务。我成功地获得了属于我项目的所有里程碑。

    这是我的 ProjectsController:

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

    我在模型中建立了所有关系:

    项目模型:

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

    里程碑型号:

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

    任务模型:

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

1 个答案:

答案 0 :(得分:2)

您可以在 eager loading

时指定多个(嵌套的)关系
$project = Project::with(['milestones', 'milestones.tasks'])->findOrFail($id);

让我们修补它:

[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'
//         )
//       )
//     )
//   )
// )
相关问题