列
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 关系是如何工作的,以及如何雄辩地检测哪条记录属于哪条父记录。
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();
列和过滤可能会根据您的需要而有所不同,您可能想要使用左连接或更改查询。