将下列代码写到文件复制到项目 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. volatile 与 JVM 指令重排序

    前言: 在做单例模式时 有博客在评论区 推荐使用 volatile 关键字 进行修饰 然后用了两天时间查资料看文档 发现涉及的面太广 虽然已经了解为什么要使用 volatile + synchroni ...

  2. generator mybatis逆向工程

    mybatis逆向工程:根据数据库中的表在项目中生成对应的 实体类,dao接口与mapper.xml映射文件 在eclipse中,以插件的形式的存在,把设置好的配置文件,直接通过eclipse中的插件 ...

  3. 对弈的C++学习笔记

    2018-07-11上传   一:从C到C++ 1.C++新类型 bool 判断真假 占用一个字节      if(条件) 真1或者假 0     bool 类型的取值 true false      ...

  4. python cmd的各种实现方法及优劣

    Python_cmd的各种实现方法及优劣(subprocess.Popen, os.system和commands.getstatusoutput)   目前我使用到的python中执行cmd的方式有 ...

  5. vue数据修改 但未渲染页面

    1. 普通的 `1.1 this.$set('obj',key,value); 1.2 this.splice(); 2.数据层次太多,没有触发render函数进行自动更新,需手动调用: this.$ ...

  6. 说一下syslog日志吧~~~

    # -*- coding:utf-8 -*-from logging.handlers import *import loggingimport logging.handlers class MySo ...

  7. ionic3 应用内打开第三方地图导航 百度 高德

    1.安装检测第三方APP是否存在的插件 cordova plugin add cordova-plugin-appavailability --save npm install --save @ion ...

  8. Labview-vi的可重入性

    VI可重入性: labview多线程中 同时对一个子vi访问时,可能会造成同时对同一块内存地址读写所造成的数据混乱,当选择 vi属性(Ctrl+i)中执行选项卡允许可重入时,labview会分配不同的 ...

  9. 抽象鸡类 abstract(抽象) base(基础) class(类型)

    # --> ''' class interface 接口: 建立关联的桥梁, 方便管理代码 (python中没有接口语法) 接口类: 用来定义功能的类 为继承它的子类提供功能 该类的功能法方法一 ...

  10. Web服务器软件 (Tomcat)

    1.什么是服务器? 安装了服务器的软件的计算机 服务器软件:接收用户的请求(request),处理请求,做出响应. Web服务器软件:接收用户的请求(request),处理请求,做出响应,再Web服务 ...