Laravel查询如何按id与created_at将3条TimesheetsDetail数据合并为视图1行
解决方案
你可以根据业务场景选择以下两种实现方式:
方式1:SQL层面直接分组聚合
如果仅需要合并数据表本身的字段,直接修改查询添加分组和聚合逻辑即可:
$query = TimesheetsDetail::with('operator_proyek.operator','operator_proyek.unit.tipe_unit') ->where('timesheets_id', $timesheets->id) // 替换下方占位字段为你实际需要合并的业务字段 ->selectRaw('id, created_at, timesheets_id, MAX(数值字段1) as 数值字段1, MAX(数值字段2) as 数值字段2, GROUP_CONCAT(文本字段 SEPARATOR ",") as 合并文本字段') ->groupBy('id', 'created_at', 'timesheets_id') ->get();
注意:如果你的数据库开启了严格模式,groupBy后需要跟上selectRaw里所有非聚合的字段
方式2:查询后用集合处理
如果合并逻辑涉及到预加载的关联数据,用SQL分组不好实现的话,可以先查全量数据再用Laravel集合方法合并:
// 先查询全部符合条件的原始数据 $detailList = TimesheetsDetail::with('operator_proyek.operator','operator_proyek.unit.tipe_unit') ->where('timesheets_id', $timesheets->id) ->get(); // 按id+created_at分组后自定义合并逻辑 $mergedList = $detailList->groupBy(function ($item) { return $item->id . '-' . $item->created_at->getTimestamp(); })->map(function ($groupItems) { $baseItem = $groupItems->first(); // 示例合并逻辑,可根据需求自行调整 $baseItem->total_duration = $groupItems->sum('duration'); $baseItem->all_work_types = $groupItems->pluck('work_type')->unique()->implode(','); return $baseItem; })->values();
内容的提问来源于stack exchange,提问作者mactavich
相关产品推荐
相关产品推荐

