GenerateModelAnnotation.php 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  1. <?php
  2. namespace UCore\Commands;
  3. use Illuminate\Console\Command;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\File;
  7. use Illuminate\Support\Facades\Log;
  8. use UCore\ModelCore;
  9. /**
  10. * 自动生成Eloquent模型属性注释和表创建SQL
  11. *
  12. * 通过分析数据库表结构,自动生成模型属性的PHPDoc注释,
  13. * 并提供fillable字段自动维护功能。同时,为每个表生成创建SQL文件。
  14. *
  15. * 功能特性:
  16. * 1. 自动识别字段类型并生成对应property注释
  17. * 2. 特殊时间字段自动识别为Carbon类型
  18. * 3. 支持自定义Casts类型,自动识别并使用正确的类型
  19. * 4. 自动维护模型$attrlist属性包含所有字段
  20. * 5. 在模块的Databases/createsql目录下为每个表生成创建SQL文件
  21. * 6. 支持指定单一模块进行处理,提高效率
  22. *
  23. * 使用说明:
  24. * 1. 在模型中添加标记注释:
  25. * - 属性注释区域标记:在模型文件中添加 field start 和 field end 注释块
  26. * - fillable字段标记:在模型文件中添加 attrlist start 和 attrlist end 注释块
  27. * 2. 对于使用自定义Cast类的字段,会自动识别并使用Cast类作为类型
  28. * 3. 可以通过指定模块名称参数,只处理特定模块的模型
  29. *
  30. * @package UCore\Commands
  31. *
  32. * @example 处理所有模块: php artisan ucore:generate-model-annotation
  33. * @example 只处理特定模块: php artisan ucore:generate-model-annotation GameItems
  34. * @example 开启调试信息: php artisan ucore:generate-model-annotation --debug-info
  35. * @example 跳过SQL生成: php artisan ucore:generate-model-annotation --skip-sql
  36. */
  37. class GenerateModelAnnotation extends Command
  38. {
  39. /**
  40. * The name and signature of the console command.
  41. *
  42. * @var string
  43. */
  44. protected $signature = 'ucore:generate-model-annotation
  45. {module? : 要处理的模块名称,不提供则处理所有模块}
  46. {--skip-sql : 跳过生成表创建SQL文件}
  47. {--debug-info : 输出详细的调试信息}';
  48. /**
  49. * The console command description.
  50. *
  51. * @var string
  52. */
  53. protected $description = '生成模型property注释和表创建SQL文件,支持自定义Casts类型,可指定单一模块处理';
  54. private $fillable = [];
  55. /**
  56. * 已处理的表名,用于避免重复生成SQL
  57. *
  58. * @var array
  59. */
  60. private $processedTables = [];
  61. /**
  62. * 成功处理的模型计数
  63. *
  64. * @var int
  65. */
  66. private $successCount = 0;
  67. /**
  68. * 跳过的模型计数
  69. *
  70. * @var int
  71. */
  72. private $skippedCount = 0;
  73. /**
  74. * 失败的模型计数
  75. *
  76. * @var int
  77. */
  78. private $failedCount = 0;
  79. /**
  80. * 主执行方法
  81. *
  82. * 扫描指定目录下的模型文件并生成注释和表创建SQL
  83. *
  84. * @return void
  85. */
  86. public function handle()
  87. {
  88. // 获取要处理的模块名称
  89. $targetModule = $this->argument('module');
  90. // 显示处理模式
  91. if ($targetModule) {
  92. $this->simpleOutput("仅处理模块: {$targetModule}");
  93. } else {
  94. $this->simpleOutput("处理所有模块");
  95. }
  96. // 显示是否跳过SQL生成的选项状态
  97. if ($this->option('skip-sql')) {
  98. $this->debug('已设置跳过生成表创建SQL文件', 'warning');
  99. } else {
  100. $this->debug('将为每个表生成创建SQL文件到模块的Databases/createsql目录');
  101. }
  102. // 如果没有指定模块或指定的是UCore,则扫描核心模型目录
  103. if (!$targetModule || strtolower($targetModule) === 'ucore') {
  104. $ucoreModelsDir = app_path('../UCore/Models');
  105. if (is_dir($ucoreModelsDir)) {
  106. $this->debug("扫描核心模型目录: $ucoreModelsDir");
  107. $this->call1($ucoreModelsDir, '\UCore\Models\\');
  108. } else {
  109. $this->simpleOutput("UCore Models 目录不存在: $ucoreModelsDir", 'warning');
  110. }
  111. }
  112. // 扫描模块下的Models目录
  113. $modulesPath = app_path('Module');
  114. if (is_dir($modulesPath)) {
  115. $modules = scandir($modulesPath);
  116. foreach ($modules as $module) {
  117. if ($module === '.' || $module === '..') {
  118. continue;
  119. }
  120. // 如果指定了模块,则只处理该模块
  121. if ($targetModule && strtolower($targetModule) !== strtolower($module)) {
  122. continue;
  123. }
  124. $modelsDir = "$modulesPath/$module/Models";
  125. if (is_dir($modelsDir)) {
  126. // 添加模块扫描日志
  127. $this->debug("扫描模块目录: $modelsDir");
  128. // 修复模块命名空间格式
  129. $namespace = "App\\Module\\$module\\Models\\";
  130. // 统一目录分隔符
  131. $namespace = str_replace('/', '\\', $namespace);
  132. // 添加自动加载提示
  133. $this->debug("请确保已配置composer自动加载: \"App\\Module\\$module\\Models\\\": \"app/Module/$module/Models/\"", 'warning');
  134. $this->call1($modelsDir, $namespace);
  135. } else if ($targetModule) {
  136. // 如果指定了模块但目录不存在,则输出警告
  137. $this->simpleOutput("模块 {$module} 的 Models 目录不存在: $modelsDir", 'warning');
  138. }
  139. }
  140. // 如果指定了模块但未找到,则输出错误
  141. if ($targetModule && $this->successCount === 0 && $this->skippedCount === 0 && $this->failedCount === 0) {
  142. $this->simpleOutput("未找到指定的模块: {$targetModule}", 'error');
  143. return;
  144. }
  145. }
  146. // 显示处理结果
  147. $this->simpleOutput("成功: {$this->successCount} | 跳过: {$this->skippedCount} | 失败: {$this->failedCount}" .
  148. (!$this->option('skip-sql') ? " | SQL文件: " . count($this->processedTables) : ""));
  149. }
  150. // ... 保持原有call1、call2、getAnnotation方法不变 ...
  151. /**
  152. * 扫描模型目录
  153. *
  154. * @param string $dir 模型文件目录路径
  155. * @param string $ns 模型类命名空间
  156. */
  157. public function call1($dir, $ns)
  158. {
  159. $this->debug("扫描目录: $dir");
  160. $list = scandir($dir);
  161. foreach ($list as $item) {
  162. if ($item === '.' || $item === '..') {
  163. continue;
  164. }
  165. $fullPath = "{$dir}/{$item}";
  166. // 递归处理子目录
  167. if (is_dir($fullPath)) {
  168. // 跳过Validator目录
  169. if (basename($fullPath) === 'Validators' || basename($fullPath) === 'Validator') {
  170. $this->debug("跳过Validator目录: $fullPath", 'warning');
  171. continue;
  172. }
  173. $this->call1($fullPath, "{$ns}{$item}\\");
  174. continue;
  175. }
  176. $p = strpos($item, '.php');
  177. if ($p !== false) {
  178. $model = substr($item, 0, $p);
  179. // 修复命名空间拼接逻辑
  180. $modelClass = rtrim($ns, '\\') . '\\' . $model;
  181. // 修复文件路径拼接
  182. $file = $fullPath;
  183. $this->call2($model, $modelClass, $file);
  184. }
  185. }
  186. }
  187. /**
  188. * 处理单个模型文件
  189. *
  190. * @param string $model 模型类名
  191. * @param string $modelClass 完整模型类名
  192. * @param string $file 模型文件路径
  193. */
  194. public function call2($model,$modelClass,$file)
  195. {
  196. if(class_exists($modelClass)){
  197. // 检查类是否是抽象类
  198. $reflectionClass = new \ReflectionClass($modelClass);
  199. if ($reflectionClass->isAbstract()) {
  200. $this->debug(" model $modelClass 是抽象类,跳过", 'warning');
  201. $this->skippedCount++;
  202. return;
  203. }
  204. // 检查类是否是模型类
  205. if (!$reflectionClass->isSubclassOf(Model::class)) {
  206. $this->debug(" model $modelClass 不是模型类,跳过", 'warning');
  207. $this->skippedCount++;
  208. return;
  209. }
  210. // 检查构造函数是否需要参数
  211. $constructor = $reflectionClass->getConstructor();
  212. if ($constructor && $constructor->getNumberOfRequiredParameters() > 0) {
  213. $this->debug(" model $modelClass 需要构造函数参数,跳过", 'warning');
  214. $this->skippedCount++;
  215. return;
  216. }
  217. /**
  218. * @var ModelCore $model
  219. */
  220. try {
  221. $model = new $modelClass();
  222. } catch (\Throwable $e) {
  223. $this->output->writeln("<fg=red>失败: " . $e->getMessage() . "</>");
  224. $this->failedCount++;
  225. return;
  226. }
  227. if($model instanceof Model){
  228. $co = $model->getConnection();
  229. $tTablePrefix = $co->getTablePrefix();
  230. $table = $tTablePrefix.$model->getTable();
  231. $this->output->write("表: $table ... ");
  232. // 提取模块名称
  233. $moduleName = $this->extractModuleNameFromNamespace($modelClass);
  234. // 如果不跳过SQL生成且找到了模块名称,则生成表的创建SQL
  235. if (!$this->option('skip-sql') && $moduleName) {
  236. // 获取无前缀的表名
  237. $tableWithoutPrefix = $model->getTable();
  238. $this->generateTableSQLFile($table, $moduleName, $co, $tableWithoutPrefix, $modelClass);
  239. }
  240. $annotation = $this->getAnnotation($table, $co, $model);
  241. $string = file_get_contents($file);
  242. // 输出文件内容的前200个字符,帮助调试
  243. $this->debug("文件内容前200字符: " . substr($string, 0, 200) . "...");
  244. // 检查文件是否包含 field start/end 标识符
  245. $hasFieldStart = strpos($string, 'field start') !== false;
  246. $hasFieldEnd = strpos($string, 'field end') !== false;
  247. $this->debug("包含 field start: " . ($hasFieldStart ? "是" : "否"));
  248. $this->debug("包含 field end: " . ($hasFieldEnd ? "是" : "否"));
  249. // 使用正则表达式匹配 field start/end 标识符
  250. $pattern = '/field\s+start[\s\S]+?field\s+end/';
  251. $this->debug("使用正则表达式匹配 field start/end: {$pattern}");
  252. // 尝试匹配
  253. $matches = [];
  254. $matchResult = preg_match($pattern, $string, $matches);
  255. $this->debug("正则匹配结果: " . ($matchResult ? "成功" : "失败"));
  256. if ($matchResult) {
  257. $this->debug("匹配到的内容长度: " . strlen($matches[0]));
  258. $this->debug("匹配到的内容前50字符: " . substr($matches[0], 0, 50) . "...");
  259. }
  260. // 替换 field start/end 标识符
  261. $replacement = "field start {$annotation} * field end";
  262. $result = preg_replace($pattern, $replacement, $string);
  263. // 检查替换是否成功
  264. $this->debug("field start/end 替换结果: 成功");
  265. // 过滤系统默认字段
  266. $filteredFillable = array_filter($this->fillable, fn($field) =>
  267. !in_array($field, ['created_at', 'updated_at', 'deleted_at'])
  268. );
  269. // 格式化数组输出
  270. $fillableContent = " protected \$fillable = [\n";
  271. foreach ($filteredFillable as $field) {
  272. $fillableContent .= " '{$field}',\n";
  273. }
  274. $fillableContent .= " ];";
  275. // 检查文件是否包含 attrlist start/end 标识符
  276. $hasAttrlistStart = strpos($string, 'attrlist start') !== false;
  277. $hasAttrlistEnd = strpos($string, 'attrlist end') !== false;
  278. $this->debug("包含 attrlist start: " . ($hasAttrlistStart ? "是" : "否"));
  279. $this->debug("包含 attrlist end: " . ($hasAttrlistEnd ? "是" : "否"));
  280. // 使用正则表达式匹配 attrlist start/end 标识符
  281. $pattern2 = '/\/\/\s*attrlist\s+start[\s\S]+?\/\/\s*attrlist\s+end/';
  282. $this->debug("使用正则表达式匹配 attrlist start/end: {$pattern2}");
  283. // 尝试匹配
  284. $matches2 = [];
  285. $matchResult2 = preg_match($pattern2, $result, $matches2);
  286. $this->debug("正则匹配结果: " . ($matchResult2 ? "成功" : "失败"));
  287. if ($matchResult2) {
  288. $this->debug("匹配到的内容长度: " . strlen($matches2[0]));
  289. $this->debug("匹配到的内容前50字符: " . substr($matches2[0], 0, 50) . "...");
  290. }
  291. // 替换 attrlist start/end 标识符
  292. $replacement2 = "// attrlist start \n{$fillableContent}\n // attrlist end";
  293. $result = preg_replace($pattern2, $replacement2, $result);
  294. // 检查替换是否成功
  295. $this->debug("attrlist start/end 替换结果: 成功");
  296. // 强制写入文件
  297. file_put_contents($file,$result);
  298. $this->successCount++;
  299. $this->output->writeln("<fg=green>完成</>");
  300. }else{
  301. $this->output->writeln("<fg=yellow>跳过: 不是继承 ModelBase</>");
  302. $this->skippedCount++;
  303. }
  304. }else{
  305. $this->debug(" model $model 不存在", 'warning');
  306. $this->skippedCount++;
  307. }
  308. }
  309. /**
  310. * 从模型命名空间中提取模块名称
  311. *
  312. * @param string $modelClass 模型类名
  313. * @return string|null 模块名称,如果不是模块内的模型则返回null
  314. */
  315. protected function extractModuleNameFromNamespace($modelClass)
  316. {
  317. // 匹配 App\Module\{ModuleName}\Models 格式的命名空间
  318. if (preg_match('/^App\\\\Module\\\\([^\\\\]+)\\\\Models/', $modelClass, $matches)) {
  319. return $matches[1];
  320. }
  321. return null;
  322. }
  323. /**
  324. * 输出调试信息并写入日志
  325. *
  326. * @param string $message 调试信息
  327. * @param string $type 信息类型 (info, warning, error)
  328. * @return void
  329. */
  330. protected function debug($message, $type = 'info')
  331. {
  332. // 始终写入日志
  333. $logPrefix = '[GenerateModelAnnotation] ';
  334. switch ($type) {
  335. case 'warning':
  336. Log::warning("{$logPrefix}{$message}");
  337. break;
  338. case 'error':
  339. Log::error("{$logPrefix}{$message}");
  340. break;
  341. default:
  342. Log::info("{$logPrefix}{$message}");
  343. }
  344. // 仅在启用调试信息时输出到控制台
  345. if ($this->option('debug-info')) {
  346. switch ($type) {
  347. case 'warning':
  348. $this->output->warning($message);
  349. break;
  350. case 'error':
  351. $this->output->error($message);
  352. break;
  353. default:
  354. $this->output->info($message);
  355. }
  356. }
  357. }
  358. /**
  359. * 输出简洁信息并写入日志
  360. *
  361. * @param string $message 信息内容
  362. * @param string $type 信息类型 (info, warning, error)
  363. * @return void
  364. */
  365. protected function simpleOutput($message, $type = 'info')
  366. {
  367. // 检查消息是否为空
  368. if (empty(trim($message))) {
  369. return;
  370. }
  371. // 始终写入日志
  372. $logPrefix = '[GenerateModelAnnotation] ';
  373. switch ($type) {
  374. case 'warning':
  375. Log::warning("{$logPrefix}{$message}");
  376. $this->output->writeln("<fg=yellow>{$message}</>");
  377. break;
  378. case 'error':
  379. Log::error("{$logPrefix}{$message}");
  380. $this->output->writeln("<fg=red>{$message}</>");
  381. break;
  382. default:
  383. Log::info("{$logPrefix}{$message}");
  384. $this->output->writeln($message);
  385. }
  386. }
  387. /**
  388. * 生成属性注释字符串
  389. *
  390. * @param string $tableName 数据库表名
  391. * @param \Illuminate\Database\Connection $con 数据库连接
  392. * @param Model|null $model 模型实例,用于获取 $casts 属性
  393. * @return string 生成的注释字符串
  394. * @throws \Exception 当数据库查询失败时
  395. */
  396. public function getAnnotation($tableName, \Illuminate\Database\Connection $con, $model = null)
  397. {
  398. $db = $con->getDatabaseName();
  399. $fillable = [];
  400. $sql = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS
  401. WHERE table_name = '{$tableName}' AND TABLE_SCHEMA = '{$db}'
  402. ORDER BY ORDINAL_POSITION ASC";
  403. $columns = $con->select($sql);
  404. $annotation = "";
  405. // 获取模型的 $casts 属性
  406. $casts = [];
  407. if ($model instanceof Model && method_exists($model, 'getCasts')) {
  408. $casts = $model->getCasts();
  409. $this->debug("模型 Casts: " . json_encode($casts, JSON_UNESCAPED_UNICODE));
  410. }
  411. foreach ($columns as $column) {
  412. $type = $this->getColumnType($column->DATA_TYPE);
  413. $columnName = $column->COLUMN_NAME;
  414. $fillable[] = $columnName;
  415. // 检查是否有自定义 Cast
  416. if (isset($casts[$columnName])) {
  417. $castType = $casts[$columnName];
  418. $this->debug("字段 {$columnName} 有自定义 Cast: {$castType}");
  419. $type = $this->getCastType($castType, $type);
  420. } else {
  421. $type = $this->handleSpecialColumns($columnName, $type);
  422. }
  423. $annotation .= sprintf("\n * @property %s \$%s %s",
  424. $type,
  425. $columnName,
  426. $column->COLUMN_COMMENT);
  427. }
  428. $this->fillable = $fillable;
  429. return "{$annotation}\n";
  430. }
  431. private function getColumnType($dataType)
  432. {
  433. return match($dataType) {
  434. 'int', 'tinyint', 'smallint', 'mediumint', 'bigint' => 'int',
  435. 'float', 'double', 'decimal' => 'float',
  436. 'json' => 'object|array',
  437. default => 'string'
  438. };
  439. }
  440. /**
  441. * 处理特殊列名的类型
  442. *
  443. * @param string $columnName 列名
  444. * @param string $type 默认类型
  445. * @return string 处理后的类型
  446. */
  447. private function handleSpecialColumns($columnName, $type)
  448. {
  449. if (in_array($columnName, ['created_at', 'updated_at', 'deleted_at'])) {
  450. return '\\Carbon\\Carbon';
  451. }
  452. return $type;
  453. }
  454. /**
  455. * 获取 Cast 类型对应的 PHP 类型
  456. *
  457. * @param string $castType Cast 类型
  458. * @param string $defaultType 默认类型
  459. * @return string PHP 类型
  460. */
  461. private function getCastType($castType, $defaultType)
  462. {
  463. // 处理基本类型
  464. $basicTypes = [
  465. 'int' => 'int',
  466. 'integer' => 'int',
  467. 'real' => 'float',
  468. 'float' => 'float',
  469. 'double' => 'float',
  470. 'decimal' => 'float',
  471. 'string' => 'string',
  472. 'bool' => 'bool',
  473. 'boolean' => 'bool',
  474. 'object' => 'object',
  475. 'array' => 'array',
  476. 'json' => 'array',
  477. 'collection' => 'Collection',
  478. 'date' => '\\Carbon\\Carbon',
  479. 'datetime' => '\\Carbon\\Carbon',
  480. 'timestamp' => '\\Carbon\\Carbon',
  481. 'immutable_date' => '\\Carbon\\CarbonImmutable',
  482. 'immutable_datetime' => '\\Carbon\\CarbonImmutable',
  483. 'immutable_timestamp' => '\\Carbon\\CarbonImmutable',
  484. ];
  485. if (isset($basicTypes[$castType])) {
  486. return $basicTypes[$castType];
  487. }
  488. // 处理自定义 Cast 类
  489. if (class_exists($castType)) {
  490. $this->debug("尝试解析自定义 Cast 类: {$castType}");
  491. // 检查是否是 UCore\Model\CastsAttributes 的子类
  492. if (is_subclass_of($castType, 'UCore\Model\CastsAttributes')) {
  493. $this->debug("{$castType} 是 UCore\Model\CastsAttributes 的子类");
  494. // 创建一个实例并获取其属性
  495. try {
  496. // 使用反射获取类的公共属性
  497. $reflectionClass = new \ReflectionClass($castType);
  498. $properties = $reflectionClass->getProperties(\ReflectionProperty::IS_PUBLIC);
  499. if (count($properties) > 0) {
  500. $this->debug("Cast 类 {$castType} 有 " . count($properties) . " 个公共属性");
  501. return "\\". get_class(new $castType());
  502. } else {
  503. $this->debug("Cast 类 {$castType} 没有公共属性,使用类名作为类型");
  504. return $castType;
  505. }
  506. } catch (\Throwable $e) {
  507. $this->debug("无法分析 Cast 类 {$castType}: " . $e->getMessage(), 'warning');
  508. }
  509. } else if (in_array('Illuminate\Contracts\Database\Eloquent\CastsAttributes', class_implements($castType))) {
  510. // 检查是否是 Illuminate\Contracts\Database\Eloquent\CastsAttributes 的实现
  511. $this->debug("{$castType} 实现了 Illuminate\Contracts\Database\Eloquent\CastsAttributes 接口");
  512. return $castType;
  513. }
  514. }
  515. // 如果无法确定类型,返回默认类型
  516. $this->debug("无法确定 Cast 类型 {$castType},使用默认类型 {$defaultType}", 'warning');
  517. return $defaultType;
  518. }
  519. /**
  520. * 获取表的创建SQL语句
  521. *
  522. * @param string $tableName 表名
  523. * @param \Illuminate\Database\Connection $connection 数据库连接
  524. * @return string 创建表的SQL语句
  525. */
  526. protected function getCreateTableSQL($tableName, $connection)
  527. {
  528. try {
  529. $result = $connection->select("SHOW CREATE TABLE `{$tableName}`");
  530. if (!empty($result) && isset($result[0]->{'Create Table'})) {
  531. return $result[0]->{'Create Table'};
  532. }
  533. } catch (\Exception $e) {
  534. $this->output->writeln("<fg=red>获取表 {$tableName} 的创建SQL失败: " . $e->getMessage() . "</>");
  535. }
  536. return null;
  537. }
  538. /**
  539. * 为表生成创建SQL文件
  540. *
  541. * @param string $tableName 表名(带前缀)
  542. * @param string $moduleName 模块名
  543. * @param \Illuminate\Database\Connection $connection 数据库连接
  544. * @param string $tableNameWithoutPrefix 无前缀的表名(必传)
  545. * @param string $modelClass 模型类名
  546. * @return void
  547. */
  548. protected function generateTableSQLFile($tableName, $moduleName, $connection, $tableNameWithoutPrefix, $modelClass = null)
  549. {
  550. // 标记该表已处理
  551. $this->processedTables[] = $tableName;
  552. // 获取表的创建SQL
  553. $createSQL = $this->getCreateTableSQL($tableName, $connection);
  554. if (empty($createSQL)) {
  555. $modelInfo = $modelClass ? " (Model: {$modelClass})" : "";
  556. $this->output->writeln("<fg=yellow>SQL生成失败{$modelInfo}</>");
  557. return;
  558. }
  559. // 创建模块的Databases/GenerateSql 目录
  560. $sqlDir = app_path("Module/{$moduleName}/Databases/GenerateSql");
  561. if (!File::exists($sqlDir)) {
  562. $this->debug("创建目录: {$sqlDir}");
  563. File::makeDirectory($sqlDir, 0755, true);
  564. }
  565. // 创建或更新README.md文件,声明该目录是自动生成的,不能修改
  566. $readmePath = "{$sqlDir}/README.md";
  567. $readmeContent = "# 自动生成的SQL文件目录\n\n";
  568. $readmeContent .= "**警告:这是自动生成的目录,请勿手动修改此目录下的任何文件!**\n\n";
  569. $readmeContent .= "此目录下的SQL文件由系统自动生成,用于记录数据库表结构。\n";
  570. $readmeContent .= "如需修改表结构,请修改对应的模型文件,然后重新运行生成命令。\n";
  571. // 只有当README.md不存在或内容不同时才写入文件
  572. if (!File::exists($readmePath) || File::get($readmePath) !== $readmeContent) {
  573. File::put($readmePath, $readmeContent);
  574. $this->debug("已创建/更新README.md文件: {$readmePath}");
  575. }
  576. // 生成SQL文件,使用无前缀的表名作为文件名
  577. $sqlFile = "{$sqlDir}/{$tableNameWithoutPrefix}.sql";
  578. // 构建SQL文件内容,添加Model信息和禁止修改声明
  579. $sqlContent = "-- ******************************************************************\n";
  580. $sqlContent .= "-- 表 {$tableName} 的创建SQL\n";
  581. if ($modelClass) {
  582. $sqlContent .= "-- 对应的Model: {$modelClass}\n";
  583. }
  584. $sqlContent .= "-- 警告: 此文件由系统自动生成,禁止修改!\n";
  585. $sqlContent .= "-- ******************************************************************\n\n";
  586. // $sqlContent .= "DROP TABLE IF EXISTS `{$tableName}`;\n";
  587. $sqlContent .= "{$createSQL};\n";
  588. File::put($sqlFile, $sqlContent);
  589. $this->debug("已生成SQL: {$sqlFile} (无前缀表名: {$tableNameWithoutPrefix})");
  590. }
  591. }