将下列代码写到文件复制到项目 console\controller 目录下:

<?php
namespace console\controllers;
use Yii;
use yii\console\Controller;
use yii\gii\CodeFile;
use yii\helpers\Console;
use yii\gii\generators\model\Generator;
use yii\gii\generators\crud\Generator as CrudGenerator;
class AutoGiiController extends Controller
{
/**
* 不创建模型的表
* @var array
*/
public $blackModelTables = [
'auth_assignment',
'auth_item',
'auth_item_child',
'auth_rule',
'banner',
'menu',
'member',
'user',
'miniProgram',
'region',
];
/**
* 不创建的crud的table 黑名单
* @var array
*/
public $blackCrudTables = [
'auth_assignment',
'auth_item',
'auth_item_child',
'auth_rule',
'banner',
'menu',
'member',
'user',
'miniProgram',
'region',
];
/**
* 生成所有 model
* actionModel
* @throws \yii\base\NotSupportedException
*/
public function actionModel()
{
$tables = Yii::$app->db->getSchema()->tableNames;
foreach ( $tables as $table ) {
if(in_array($table,$this->blackModelTables)){
continue;
}
try {
$generator = new Generator();
//配置模板
$generator->templates = [
'Absolute' => Yii::getAlias('@backend/components/giiTemplate/Absolute/model/default')
];
$generator->baseClass = '\common\models\BaseActiveRecord'; //父类文件
$generator->template = 'Absolute'; //模板
$generator->queryNs = 'common\models'; //命名空间
$generator->ns = 'common\models'; //命名空间
$generator->modelClass = $this->formatTableName($table); //格式化类名
$generator->tableName = $table;
$files = $generator->generate();
$n = count($files);
if ( $n === 0 ) {
$this->stdout("\n {$table} 没有文件要生成.", Console::FG_RED);
continue;
}
/** @var CodeFile $file */
foreach ( $files as $file ) {
$file->getRelativePath();
$this->writeContentFile($file->path, $file->content);
}
} catch ( \Exception $e ) {
$this->stdout("\n {$table} 生成失败.". "\n", Console::FG_RED);
$this->stdout("\n" . $e->getTraceAsString() . "\n", Console::FG_RED);
$this->stdout("\n" . $e->getMessage() . "\n", Console::FG_RED);
break;
}
}
}
/**
* 格式化表名
* formatTableName
* @param $tableName
* @return mixed
*/
protected function formatTableName($tableName)
{
$tableName = str_replace('_', ' ', $tableName);
$tableName = str_replace('-', ' ', $tableName);
$tableName = ucwords($tableName);
return str_replace(' ', '', $tableName);
}
/**
* 生成所有 crud
* actionCrud
* @throws \yii\base\NotSupportedException
*/
public function actionCrud()
{
$tables = Yii::$app->db->getSchema()->tableNames;
foreach ( $tables as $table ) {
if(in_array($table,$this->blackCrudTables)){
continue;
}
try {
$generator = new CrudGenerator();
$generator->templates = [
'Absolute' => Yii::getAlias('@backend/components/giiTemplate/Absolute/crud/default'),
];
$tableName = $this->formatTableName($table);
$this->writeModelFile($tableName);
$generator->template = 'Absolute'; //模板
$generator->modelClass = "backend\models\\".$tableName; //模型类
$generator->controllerClass = "backend\controllers\\".$tableName."Controller"; //控制器名称
$generator->viewPath = $this->formatViewPath($tableName); //视图路径
$generator->baseControllerClass = "backend\controllers\\BackendController"; //父控制器
$generator->searchModelClass = "backend\models\search\\".$tableName."Search"; //搜索模型名称
$files = $generator->generate();
$n = count($files);
if ( $n === 0 ) {
$this->stdout("\n {$table} 没有文件要生成.", Console::FG_RED);
continue;
}
/** @var CodeFile $file */
foreach ( $files as $file ) {
$file->getRelativePath();
$this->writeContentFile($file->path, $file->content);
}
}catch ( \Exception $e ) {
$this->stdout("\n {$table} 生成失败.". "\n", Console::FG_RED);
$this->stdout("\n" . $e->getTraceAsString() . "\n", Console::FG_RED);
$this->stdout("\n" . $e->getMessage() . "\n", Console::FG_RED);
break;
}
}
}
/**
* 格式视图路径名称
* formatViewPath
* @param $tableName
* @return bool|string
* @throws \Exception
*/
protected function formatViewPath($tableName)
{
$dir = Yii::getAlias("@backend/views/".strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '-', $tableName)));
if (!is_dir($dir)) {
$mask = @umask(0);
$result = @mkdir($dir, 0777, true);
@umask($mask);
if (!$result) {
throw new \Exception("Unable to create the directory '$dir'.");
}
}
return $dir;
}
/**
* writeModelFile
* 复制 父类模型 文件
* @param $tableName
* @throws \Exception
*/
protected function writeModelFile($tableName)
{
$backendModelFile = Yii::getAlias("@backend/models/".$tableName.".php");
if(!is_file($backendModelFile)){
$content = <<<PHP
<?php
namespace backend\models;
use Yii;
class {$tableName} extends \common\models\\{$tableName}
{
}
PHP;
$this->writeContentFile($backendModelFile,$content);
}
}
/**
* writeContentFile
* @param $file
* @param $content
* @throws \Exception
*/
protected function writeContentFile($file,$content)
{
if (@file_put_contents($file, $content) === false) {
throw new \Exception("写入文件到 '{$file}' 错误.");
}
$mask = @umask(0);
@chmod($file, 0666);
@umask($mask);
$this->stdout("\n 生成文件 {$file} 成功 \n", Console::FG_GREEN);
}
}

  

执行命令:

//创建model
php yii auto-gii/model //创建crud
php yii auto-gii/crud

  

创建的model说明:只是在common下生成,并且继承自己重写 \yii\db\ActiveRecord 的父类模型文件 BaseActiveRecord, 创建crud,在backend的model目录写一个模型文件继承 common\model 目录下的模型文件。自己使用要根据业务需求更改 没做命令行匹配,改的频率很低,代码都有注释。 效果:

命令生成所有数据库表模型以及 CRUD的更多相关文章

  1. EF 控制code-first生成的数据库表名的单复数

    原地址:https://blog.csdn.net/winnyrain/article/details/51248410 在Code-First中,默认生成的数据库表的名称为类型的复数形式,如Mode ...

  2. JAVA 自动生成对应数据库表的JPA代码工具

    http://blog.csdn.net/zheng2008hua/article/details/6274659 关键词:JPA 数据库表代码自动生成,JPA代码生成     自动生成对应数据库表的 ...

  3. 使用PD(PowerDesigner)图如何快速生成创建数据库表的SQL脚本

    打开PD软件: 1.新建概念模型(conceptual Data Model) File-->New Model-->Conceptual Data Mode 或者点击工作区,右键--&g ...

  4. Excel生成Oracle数据库表sql工具类

    1.解决问题: 开发文档中字段比较多的时候,建表sql(Oracle下划线命名规范)比较麻烦,容易出错~~ (主要是懒) 特意手写一个工具,根据excel字段,生成建表的sql语句. ~~~末尾附Gi ...

  5. 02 . 02 . Go之Gin+Vue开发一个线上外卖应用(集成第三方发送短信和xorm生成存储数据库表)

    集成第三方发送短信 介绍 用户登录 用户登录有两种方式: 短信登录,密码登录 短信登录是使用手机号和验证码进行登录 短信平台 很多云平台,比如阿里云,腾讯云,七牛云等云厂商,向程序开发者提供了短信验证 ...

  6. 用sql语句生成sqlserver数据库表的数据字典

    THEN O.name ELSE N'' END, 表描述 THEN PTB.[value] END,N''), 字段序号=C.column_id, 字段名称=C.name, 字段描述=ISNULL( ...

  7. PowerDesigner逆向生成MYSQL数据库表结构总结

    由于日常数据建模经常使用PowerDesigner,使用逆向工程能更加快速的生成模型提高效率,所以总结使用如下: 1.      安装MYSQL的ODBC驱动 Connector/ODBC 5.1.1 ...

  8. 用T4模版生成对应数据库表的实体类

    <#@ template debug="false" hostspecific="false" language="C#" #> ...

  9. mysql cmd命令行 创建数据库 表 基础语句

    一.连接MYSQL 格式: mysql -h主机地址 -u用户名 -p用户密码 1. 连接到本机上的MYSQL. 首先打开DOS窗口,然后进入目录mysql\bin,再键入命令mysql -u roo ...

随机推荐

  1. L1-064 估值一亿的AI核心代码

    以上图片来自新浪微博. 本题要求你实现一个稍微更值钱一点的 AI 英文问答程序,规则是: 无论用户说什么,首先把对方说的话在一行中原样打印出来: 消除原文中多余空格:把相邻单词间的多个空格换成 1 个 ...

  2. java中的异常处理问题。

    异常处理--基本概念 当出现程序无法控制的外部环境问题(用户提供的文件不存在,文件内容损坏,网络不可用...)时,JAVA就会用异常对象来描述. java中用2种方法处理异常: 1.在发生异常的地方直 ...

  3. Linux:Gentoo系统的安装笔记(二)

    这期笔记继续安装Gentoo,上期我们已经到了可以进入新环境了,这意味着就是将原来的安装CD或其它介质改为硬盘上安装系统了,话不多说,马上开始! 恢复安装 由于我已经中断了安装,对于已经可以进入新环境 ...

  4. MySQL 把两个结果集拼接到一起(两个结果集的列一模一样)

    select * from a UNION all ( select * from b)

  5. ubuntu 18.04启动samba图形管理界面

    启动samba图形界面管理器出现错误: Failed to load module "canberra-gtk-module" 或 SystemError: could not o ...

  6. Python 进程池的回调函数

    import os from multiprocessing import Pool,Process def f1(n): print('进程池里面的进程id',os.getpid()) print( ...

  7. css缩放的坑

    transform:scale()缩放后会往中间聚集.transform-origin: top left可以让他看上去是沿着左上角缩放. .zoom { transform: scale(.8); ...

  8. svg 动画 透明度 放大缩小 x轴Y轴

    参考链接:https://www.cnblogs.com/Chrimisia/p/6670303.html vue 中封装svg:http://www.cnblogs.com/Jiangchuanwe ...

  9. 测试计划的编写6要素(5W1H)

    Why --为什么要进行这些测试 WHat--测试哪些内容 When--测试不同阶段的起止时间 WHere--相应文档,缺陷的存放位置,测试环境 Who--项目有关人员组成 How--如何去做,使用哪 ...

  10. 停止node进程和查看react-native-cli

    taskkill /f /t /im node.exe which react-native