我有适用的代码,但没有急切加载嵌套关系。
$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();
答案 0 :(得分:5)
这样的事情应该有效。
$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)
。