GenerateModelAnnotation.php 24 KB

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