Laravel Sum 主表和关系表

问题描述 投票:0回答:1

pups_born
位于主表
Delivery

关系表

weaned_male

 中的
weaned_female
Weaning

在主表中按

date_of_delivery
分组,我想要
pups_born
weaned_male
weaned_female

的总和结果
Delivery::with(['weaning' => function ($q) {
             $q->selectRaw('SUM(weaned_male) as total_weaned_male, SUM(weaned_female) as total_weaned_female');
    }])->selectRaw('*, sum(pups_born) as total_pups_born')->groupBy('date_of_delivery')->orderBy('date_of_delivery','desc')->get()

如何获取关系表的总和以及主表的总和?

laravel eloquent eloquent-relationship
1个回答
0
投票

这个解决方案甚至行不通,原因是你需要知道 Laravel 关系是如何工作的,以及如何雄辩地检测哪条记录属于哪条父记录。

laravel 关系由

local key
foreign key
检测,并且可以在模型中显式设置。

但是在关系的 selectRaw 中你忽略了外键。

解决方案是使用 join,查询将是这样的:

Delivery::query()
    ->selectRaw('SUM(weaned_male) as total_weaned_male, SUM(weaned_female) as total_weaned_female, sum(pups_born) as total_pups_born')
    ->join('weanings', 'deliveries.weaning_id', '=', 'weanings.id')
    ->groupBy('date_of_delivery')
    ->get();

列和过滤可能会根据您的需要而有所不同,您可能想要使用左连接或更改查询。

© www.soinside.com 2019 - 2024. All rights reserved.