gpt4 book ai didi

Laravel 急切加载嵌套关系与自定义查询

转载 作者:行者123 更新时间:2023-12-02 01:00:55 32 4
gpt4 key购买 nike

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

$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 和 score),我会这样做

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

但问题出现在那些自定义选择(score 和 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) 使用($arg)

关于Laravel 急切加载嵌套关系与自定义查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28801252/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com