makeModel.php 2.9 KB

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