subDays(3)->startOfDay(); // 查询三天前的日期列表 $dates = Db::table('user_phone_log') ->selectRaw('DATE(created_at) AS date') ->where('created_at', '<', $threeDaysAgo) ->groupByRaw('DATE(created_at)') ->orderBy('date') ->get(); // 遍历每个日期 foreach ($dates as $v) { $date = $v->date; // 使用 Carbon 获取当天的开始和结束时间 $startOfDay = Carbon::parse($date)->startOfDay(); $endOfDay = Carbon::parse($date)->endOfDay(); // 查询当天的日志记录,并按手机号汇总在线时间 $logs = UserPhoneLog::whereBetween('created_at', [$startOfDay, $endOfDay]) ->selectRaw('phone, SUM(time) AS total_time') ->groupBy('phone') ->get(); // 准备批量插入的数据 $batchData = []; foreach ($logs as $log) { $batchData[] = [ 'phone' => $log->phone, 'created_at' => $startOfDay, 'updated_at' => $startOfDay, 'time' => $log->total_time, ]; } // 开始数据库事务 Db::beginTransaction(); try { // 批量插入数据到 user_phone_day_log 表 if (!empty($batchData)) { UserPhoneDayLog::insert($batchData); } // 删除已处理的日志记录 UserPhoneLog::whereBetween('created_at', [$startOfDay, $endOfDay])->delete(); // 提交事务 Db::commit(); } catch (Exception $e) { // 发生异常,回滚事务 Db::rollBack(); // 记录错误日志 Log::error("Error processing date {$date}: " . $e->getMessage()); } } return ApiResponseApp::success([]); } }