makeModel.php 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. <?php
  2. declare (strict_types = 1);
  3. namespace app\command;
  4. use think\console\Command;
  5. use think\console\Input;
  6. use think\console\input\Argument;
  7. use think\console\input\Option;
  8. use think\console\Output;use think\facade\Db;use think\facade\Env;
  9. class makeModel extends Command
  10. {
  11. protected function configure()
  12. {
  13. // 指令配置
  14. $this->setName('makemodel')
  15. ->setDescription('the makemodel command');
  16. }
  17. static $schema = 'sys_user_pre_release';
  18. static $prefix = 'sys';
  19. static $epp = 'user';
  20. protected function execute(Input $input, Output $output)
  21. {
  22. //获取表名
  23. $tables = Db::query("SELECT TABLE_NAME as 'name'
  24. from information_schema.tables
  25. WHERE TABLE_SCHEMA = :dataBase and TABLE_TYPE='BASE TABLE'", ['dataBase' => self::$schema]);
  26. echo Db::getLastSql();
  27. foreach ($tables as $key => $value) {
  28. foreach ($value as $item) {
  29. //获取字段名称和备注
  30. $COLUMNS = Db::query('select COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT
  31. from information_schema.COLUMNS
  32. where table_name = :item
  33. and table_schema = :dataBase', ['item' => $item, 'dataBase' => self::$schema]);
  34. $dir = app_path().self::$epp."/model/". self::snakeToCamel($item) . '.php';
  35. if(file_exists($dir)) continue;
  36. $file = fopen($dir, 'w');
  37. fwrite($file, '<?php' . PHP_EOL . 'namespace app\\' . self::$epp . '\model;' . PHP_EOL
  38. . PHP_EOL . 'class ' . self::snakeToCamel($item) . ' extends Base'
  39. . PHP_EOL . '{' . PHP_EOL);
  40. $content = '//设置字段信息' . PHP_EOL .
  41. ' protected $' . 'schema = [' . PHP_EOL;
  42. fwrite($file, $content);
  43. //写入字段
  44. foreach ($COLUMNS as $COLUMN) {
  45. $content = " '" . $COLUMN['COLUMN_NAME'] . "'" . ' =>' ."'" . $COLUMN['DATA_TYPE'] . "'" . ',' . '//' . $COLUMN['COLUMN_COMMENT'] . PHP_EOL;
  46. fwrite($file, $content);
  47. }
  48. $content = ' ];';
  49. fwrite($file, $content);
  50. fwrite($file, PHP_EOL . '}');
  51. fclose($file);
  52. }
  53. }
  54. }
  55. private static function snakeToCamel($str, $capitalized = true)
  56. {
  57. $result = ucwords(str_replace(['_',self::$prefix], ['',""],$str),"_");
  58. echo $result."--";
  59. echo str_replace(['_',self::$prefix], ['',''],$str);
  60. if (!$capitalized) {
  61. $result = lcfirst($result);
  62. }
  63. return $result;
  64. }
  65. }