【发布时间】:2021-08-10 06:09:05
【问题描述】:
我正在使用 Laravel 5.6 和 postgres 11。
我记录了不同设备类型的数量变化,如下所示:
{location_id: 1, equipment_type_id: 1, qty: 5, total: 5, date: 'YYYY-MM-DD'},
{location_id: 1, equipment_type_id: 1, qty: 5, total: 10, date: 'YYYY-MM-DD'},
{location_id: 1, equipment_type_id: 2, qty: 5, total: 5, date: 'YYYY-MM-DD'},
{location_id: 1, equipment_type_id: 1, qty: 5, total: 15, date: 'YYYY-MM-DD'} etc
我希望能够获得按月分组的每种类型的总数,但我只想获得同一个月内某个类型和位置的最新总数。例如,如果位置 1 有 3 个类型 1 的条目,我想总结该月的最后一个条目。
返回的数据如下所示:
{type: 1, data: [{month: Jan, total: 15}]},
{type: 2, data: [{month: Jan, total: 10},{month: Feb, total: 15}]}
我很快就开始了,但这种类型的查询完全超出了我的想象:
$singles = EquipmentLog::where('equipment_type_id', '=', 3)
->select(
DB::raw('sum(total) as total'),
DB::raw("DATE_TRUNC('month',logged_at) as month")
)
->groupBy('month')
->get();
$totals = [
['name' => 'Hives - Single', 'data' => $singles],
];
【问题讨论】:
-
我对这个问题有点困惑。是否要检索类型和位置的最后一个条目?
-
@SandeepDhakal 很抱歉造成混淆,我想要每种类型的总数,但只使用一个月内每个位置的最后一个条目。希望这更有意义?
标签: laravel postgresql laravel-5 eloquent