where('table_name', $tableName) ->find(); if (!$tableInfo) { Db::name('vs_give_gift_tables')->insert([ 'table_name' => $tableName, 'start_time' => $startTime, 'end_time' => $endTime, 'create_time' => time() ]); } Log::info("创建分表成功: {$tableName}"); return true; } catch (\Exception $e) { Log::error("创建分表失败 {$tableName}: " . $e->getMessage()); throw new Exception('创建分表失败:' . $e->getMessage()); } } /** * 批量创建分表 * @param int $months 创建未来几个月 * @return array 创建结果 */ public static function batchCreateTables($months = 12) { $results = []; for ($i = 0; $i < $months; $i++) { $yearMonth = date('Ym', strtotime("+{$i} month")); try { $result = self::createMonthTable($yearMonth); $results[$yearMonth] = [ 'success' => $result, 'message' => $result ? '创建成功' : '创建失败' ]; } catch (\Exception $e) { $results[$yearMonth] = [ 'success' => false, 'message' => $e->getMessage() ]; } } return $results; } /** * 获取所有分表 * @return array */ public static function getAllTables() { try { return Db::name('vs_give_gift_tables') ->order('start_time', 'asc') ->select(); } catch (\Exception $e) { Log::error("获取分表列表失败: " . $e->getMessage()); return []; } } /** * 根据时间范围获取需要查询的表 * @param int $startTime 开始时间戳 * @param int $endTime 结束时间戳 * @return array 表名数组 */ public static function getTablesByTimeRange($startTime = null, $endTime = null) { try { $query = Db::name('vs_give_gift_tables'); if ($startTime !== null) { $query->where('end_time', '>=', $startTime); } if ($endTime !== null) { $query->where('start_time', '<=', $endTime); } $tables = $query->order('start_time', 'asc') ->column('table_name'); return $tables ?: []; } catch (\Exception $e) { Log::error("获取时间范围分表失败: " . $e->getMessage()); return []; } } /** * 初始化分表系统 * @param string $startMonth 起始年月 202401 * @param int $months 创建几个月 * @return array */ public static function initTables($startMonth = null, $months = 24) { if (!$startMonth) { $startMonth = date('Ym'); } $results = []; $startDate = new \DateTime($startMonth . '01'); for ($i = 0; $i < $months; $i++) { $currentDate = clone $startDate; $currentDate->modify("+{$i} month"); $yearMonth = $currentDate->format('Ym'); try { $result = self::createMonthTable($yearMonth); $results[$yearMonth] = $result; } catch (\Exception $e) { $results[$yearMonth] = false; } } return $results; } /** * 检查并创建当前月份的表 * @return bool */ public static function checkAndCreateCurrentMonthTable() { $currentMonth = date('Ym'); return self::createMonthTable($currentMonth); } }