Laravel 预加载自定义查询的嵌套关系

Laravel eager loading nested relationships with custom query

我有可用的代码,但没有急于加载嵌套关系。

$projects = Project::with('organization')
        ->leftJoin('stages', 'stages.project_id', '=', 'projects.id')
        ->leftJoin('activities', 'activities.stage_id', '=', 'stages.id')
        ->leftJoin('tasks', 'tasks.activity_id', '=', 'activities.id')
        ->select('projects.*',  DB::raw('SUM(IF(tasks.status = 4, score, 0)) AS score'), 
                                DB::raw('SUM(tasks.score) AS total_score'))
        ->groupBy('projects.id')
        ->get();

我想通过预加载嵌套关系来做到这一点,如果我没有这些自定义选择(total_score 和分数),我会这样做

$projects = Project::with('stages.activities.tasks');

但问题出现在那些自定义选择上(分数和 total_score)。 我试过类似的东西,但没用

$projects = Project::with(['stages', 'activities', 'tasks' => function($q) { 
        $q->select( DB::raw('SUM(IF(tasks.status = 4, score, 0)) AS score'), 
                    DB::raw('SUM(tasks.score) AS total_score')); 
    }])->get();

类似的东西应该可以工作:

$projects = $project::with(array('stages' => function($q)
 {
   $q->with(array('activities' => function($q)
   {
     $q->with(array('tasks' => function($q)
     {
        $q->groupBy('tasks.id');
        $q->addselect([
            DB::raw('SUM(IF(tasks.status = 4, score, 0)) AS score'),
            DB::raw('SUM(tasks.score) AS total_score')
            ]);
       }));
     }));
   }))
 ->get();

如果您的函数需要更多参数 function($q) use ($arg)