命令生成所有数据库表模型以及 CRUD
将下列代码写到文件复制到项目 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的更多相关文章
- EF 控制code-first生成的数据库表名的单复数
原地址:https://blog.csdn.net/winnyrain/article/details/51248410 在Code-First中,默认生成的数据库表的名称为类型的复数形式,如Mode ...
- JAVA 自动生成对应数据库表的JPA代码工具
http://blog.csdn.net/zheng2008hua/article/details/6274659 关键词:JPA 数据库表代码自动生成,JPA代码生成 自动生成对应数据库表的 ...
- 使用PD(PowerDesigner)图如何快速生成创建数据库表的SQL脚本
打开PD软件: 1.新建概念模型(conceptual Data Model) File-->New Model-->Conceptual Data Mode 或者点击工作区,右键--&g ...
- Excel生成Oracle数据库表sql工具类
1.解决问题: 开发文档中字段比较多的时候,建表sql(Oracle下划线命名规范)比较麻烦,容易出错~~ (主要是懒) 特意手写一个工具,根据excel字段,生成建表的sql语句. ~~~末尾附Gi ...
- 02 . 02 . Go之Gin+Vue开发一个线上外卖应用(集成第三方发送短信和xorm生成存储数据库表)
集成第三方发送短信 介绍 用户登录 用户登录有两种方式: 短信登录,密码登录 短信登录是使用手机号和验证码进行登录 短信平台 很多云平台,比如阿里云,腾讯云,七牛云等云厂商,向程序开发者提供了短信验证 ...
- 用sql语句生成sqlserver数据库表的数据字典
THEN O.name ELSE N'' END, 表描述 THEN PTB.[value] END,N''), 字段序号=C.column_id, 字段名称=C.name, 字段描述=ISNULL( ...
- PowerDesigner逆向生成MYSQL数据库表结构总结
由于日常数据建模经常使用PowerDesigner,使用逆向工程能更加快速的生成模型提高效率,所以总结使用如下: 1. 安装MYSQL的ODBC驱动 Connector/ODBC 5.1.1 ...
- 用T4模版生成对应数据库表的实体类
<#@ template debug="false" hostspecific="false" language="C#" #> ...
- mysql cmd命令行 创建数据库 表 基础语句
一.连接MYSQL 格式: mysql -h主机地址 -u用户名 -p用户密码 1. 连接到本机上的MYSQL. 首先打开DOS窗口,然后进入目录mysql\bin,再键入命令mysql -u roo ...
随机推荐
- NIO 概述 与 通信实例
NIO 简述: NIO是在jdk1.4之后加入的一种基于缓冲区(buffer)和通道(channel)的I/O方式, nio是同步非阻塞的i/o模式,同步是指线程不断地轮询i/o事件,非阻塞是在处理i ...
- .net下的缓存技术
1.为什么要缓存?缓存能解决的问题 1.1稳定性 同一个应用中,对同一数据.逻辑功能和用户界面的多次请求时经常发生的.当用户基数很大时,如果每次请求都进行处理,消耗的资源是很大的浪费,也同时造成系统的 ...
- 解决Caused by: java.lang.IllegalArgumentException: Result Maps collection does not contain value for com.geek.dao.ContentDao.Integer
mybatis报错:Caused by: java.lang.IllegalArgumentException: Result Maps collection does not contain val ...
- java后端的知识学习
有良好的计算机基础知识,熟悉计算机网络技术以及常用的设计模式:有扎实的 Java 语言基础,熟悉 Java 多线程编程技术.JVM 虚拟机原理:熟悉J2EE体系架构,熟悉WebService.Spri ...
- Touch Gesture手势总结
- 一个python小白的学习之路
本人是个网管,在佛山工作,现在已经学习了一段时间python了,还是学开基础,但近段时间有一点的突破出来了,找到了一个很好的自学视频,等自己有能力了就想找一个特训班试试.已经看了视频两个星期了,有小小 ...
- ADO.NET读取配置文件
App.config <?xml version="1.0" encoding="utf-8" ?> <configuration> & ...
- React中使用echarts
1.安装相关的依赖: cnpm i react-for-echarts -S cnpm i echarts -S 2.使用方法: 页面引入: import ReactEcharts from 'ech ...
- C#入门基本概念
一.版本号的命名规则 大部分时候是在名字后面加些数字表示不同的版本.其中以加上年份号最为简单明了.比如 Visual Studio 2008.但是大部分人还是不用这个方式.因为年份号中没有带来跟多的信 ...
- jQuery-4.动画篇---淡入淡出效果
jQuery中淡出动画fadeOut 让元素在页面不可见,常用的办法就是通过设置样式的display:none.除此之外还可以一些类似的办法可以达到这个目的.这里要提一个透明度的方法,设置元素透明度为 ...