[英]Laravel Eloquent Query Select Column From Multiple Tables
I have a Laravel backend and a VueJS frontend.我有一个 Laravel 后端和一个 VueJS 前端。
I'm trying to produce a query on a model with a hasOne relationship but only select specific columns from the relationship, do a sum and a group by.我正在尝试对具有 hasOne 关系但仅 select 特定列从关系中的 model 生成查询,进行求和和分组。
Models楷模
My Eloquent Query我的 Eloquent 查询
public function contractsByYear() {
return Contract::where('CONTRACT_TYPE','LIKE','SP-%')->with(['AdditionalInfo' => function($query) {
$query->selectRaw('MONTH(START_DATE) as Month')->whereYear('START_DATE','2019');
}])->sum('CONTRACT_PRICE')->groupBy('Month');
}
Expected Results预期成绩
MONTH | TOTAL
1 | 500
2 | 233
3 | 800
etc
My issue is the table structure is existing and I can't edit.我的问题是表结构存在,我无法编辑。 Why the START_DATe is stored in a separate table is beyond me.
为什么 START_DATe 存储在单独的表中是我无法理解的。
Collection methods will probably do what you want收集方法可能会做你想要的
public function contractsByYear()
{
return Contract::select('id', 'CONTRACT_PRICE') /* Only really need the id (or whatever else is the pk) and the price */
->where('CONTRACT_TYPE','LIKE','SP-%')
->with(['AdditionalInfo' => function($query) {
$query->select('id', 'contract_id') /* Only really need the id (or whatever else is the pk), and the Contract fk*/
->selectRaw('MONTH(START_DATE) as Month') /* Aggregate the month */
->whereYear('START_DATE','2019');
}])
->get()
// From this point on, it's a Collection
->groupBy('AdditionalInfo.*.Month') /* It's either this or 'AdditionalInfo.Month' */
->map(function($item, $key) {
return [
'month' => $key,
'total' => $item->sum('CONTRACT_PRICE')
];
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.