diff --git a/app/Http/Controllers/Admin/StatisticsController.php b/app/Http/Controllers/Admin/StatisticsController.php index bd5a5b5..22e9d28 100755 --- a/app/Http/Controllers/Admin/StatisticsController.php +++ b/app/Http/Controllers/Admin/StatisticsController.php @@ -515,35 +515,31 @@ class StatisticsController extends CommonController foreach ($productItem as $item) { foreach ($factor as $factor_item) { - $query = OrderItems::where('product_item_id', $item->id) + // 基础查询:当前项目下、当前病区床位、指定产品子项、指定月份的子订单 + $baseQuery = OrderItems::where('product_item_id', $item->id) ->whereIn("bed_id", $bedIds) ->where('paid_at', 'like', '%' . $month . '%'); - // 修复:使用 MySQL 5.7 的 JSON 函数进行精确查询(推荐方式) - // 确保 factor_item_id 是整数类型,防止SQL注入 + // 精确匹配包含指定 factor_item_id 的子订单(使用 LIKE + 参数绑定,兼容现有 JSON 结构) $factorItemId = (int) $factor_item->id; - - // 使用 JSON_SEARCH 函数精确匹配 JSON 数组中任意元素的 factor_item_id 字段 - // 参数说明: - // - factors: JSON 字段名 - // - 'one': 返回第一个匹配的路径(如果只需要判断是否存在,可以用 'one') - // - ?: 要搜索的值(factor_item_id) - // - NULL: 转义字符(不需要) - // - '$[*].factor_item_id': JSON 路径表达式,匹配数组中所有元素的 factor_item_id 字段 - $query->whereRaw("JSON_SEARCH(factors, 'one', ?, NULL, '$[*].factor_item_id') IS NOT NULL", [$factorItemId]); - - // 使用真实订单子项数据: - // 1. 总收入:该列下所有子订单的 total 求和 - // 2. 列表头价格:取该列下任意一条子订单的 total 作为真实单价 - $totalQuery = clone $query; + $baseQuery->where(function ($q) use ($factorItemId) { + // 匹配 ... "factor_item_id":1, ... 或 ... "factor_item_id":1} + $q->whereRaw("factors LIKE CONCAT('%', '\"factor_item_id\":', ?, ',%')", [$factorItemId]) + ->orWhereRaw("factors LIKE CONCAT('%', '\"factor_item_id\":', ?, '}%')", [$factorItemId]); + }); + + // 1)列对应的真实总收入:该因子 + 产品子项 + 病区 + 月份 下所有子订单的 total 之和 + $totalQuery = clone $baseQuery; $total = (float) $totalQuery->sum('total'); - $sampleItem = $query->first(); - $totalPrice = $sampleItem ? (float) $sampleItem->total : 0; + // 2)表头展示的价格:使用该列下“实际发生过的正价子订单”的最小单日价格,保证接近真实下单价格 + $priceQuery = clone $baseQuery; + $price = (float) $priceQuery->where('total', '>', 0)->min('total'); + $totalPrice = $price > 0 ? $price : 0; $list[] = [ 'name' => $totalPrice . '元/天', - 'factor_item_name' => $factor_item->name ?? '', // 添加 factor_item 的 name + 'factor_item_name' => $factor_item->name ?? '', 'total_price' => $totalPrice, 'product_item_id' => $item->id, 'factor_item_id' => $factor_item->id,