makeModel.php 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. foreach ($tables as $key => $value) {
  27. foreach ($value as $item) {
  28. //获取字段名称和备注
  29. $COLUMNS = Db::query('select COLUMN_NAME,DATA_TYPE,COLUMN_COMMENT
  30. from information_schema.COLUMNS
  31. where table_name = :item
  32. and table_schema = :dataBase', ['item' => $item, 'dataBase' => self::$schema]);
  33. $dir = app_path().self::$epp."/model/". self::snakeToCamel($item) . '.php';
  34. if(file_exists($dir)) continue;
  35. $file = fopen($dir, 'w');
  36. fwrite($file, '<?php' . PHP_EOL . 'namespace app\\' . self::$epp . '\model;' . PHP_EOL
  37. . PHP_EOL . 'class ' . self::snakeToCamel($item) . ' extends Base'
  38. . PHP_EOL . '{' . PHP_EOL);
  39. $content = '//设置字段信息' . PHP_EOL .
  40. ' protected $' . 'schema = [' . PHP_EOL;
  41. fwrite($file, $content);
  42. //写入字段
  43. foreach ($COLUMNS as $COLUMN) {
  44. $content = " '" . $COLUMN['COLUMN_NAME'] . "'" . ' =>' ."'" . $COLUMN['DATA_TYPE'] . "'" . ',' . '//' . $COLUMN['COLUMN_COMMENT'] . PHP_EOL;
  45. fwrite($file, $content);
  46. }
  47. $content = ' ];';
  48. fwrite($file, $content);
  49. fwrite($file, PHP_EOL . '}');
  50. fclose($file);
  51. }
  52. }
  53. }
  54. private static function snakeToCamel($str, $capitalized = true)
  55. {
  56. $result =str_replace(['_',self::$prefix], ['',""],ucwords($str,"_"),);
  57. echo $result."--";
  58. echo str_replace(['_',self::$prefix], ['',''],$str);
  59. if (!$capitalized) {
  60. $result = lcfirst($result);
  61. }
  62. return $result;
  63. }
  64. }