Yii2 数据库表映射为模型
使用 yii2 自带的命令 yii
中的内置命令 gii
可以将数据库中的表结构映射为 Model
类文件:
- 查看
gii
的使用帮助
$ php yii gii/model --help
DESCRIPTION
This generator generates an ActiveRecord class for the specified database
table.
USAGE
yii gii/model [...options...]
OPTIONS
......
gii/model
常用参数说明
--tableName
指定数据库中对应的表名--modelClass
指定生成的模型类名--ns
指定生成模型类的命名空间,默认为app\models
--overwrite
如果模型类已存在是否重写对应的模型类,默认为0不重写,1重写--interactive
是否以交互模式执行,默认1交互模式执行,生成类文件时会询问是否生成到本地,0 不询问直接生成
例如:假如数据库中存在一张表 address
, 我们需要生成对应的模型类 Address
。
$ php yii gii/model --tableName=address \
--modelClass=Address \
--overwrite=1 \
--interactive=0
执行完成之后,在项目的models目录下就会生成一个名为 Address.php
的模型类文件。
- 利用 shell.php 代码来执行上述 shell 命令
<?php
echo `php yii gii/model --tableName=address \
--modelClass=Address \
--overwrite=1 \
--interactive=0`;
命令行执行 php shell.php 也会得到相同的结果
- 批量生成数据库中的全部表的模型
我们可以利用 yii2 中的 commands 创建一个新的命令:DbMapController.php
:
<?php
namespace app\commands;
use yii\console\ExitCode;
use yii\console\Controller;
/**
* 将数据库表结构映射为模型类
*/
class DbMapController extends Controller
{
/**
* 默认将数据库中所有的表结构映射为模型类
* @param string $namespace
* @param string $prefix
* @return int
*/
public function actionIndex(string $namespace = "app\\models\\raw", string $prefix = ''): int
{
try {
$rst = \Yii::$app->db->createCommand("show tables")->queryAll();
} catch (\Throwable $e) {
\Yii::error($e->getMessage());
return ExitCode::UNSPECIFIED_ERROR;
}
foreach ($rst as $r) {
$tableName = array_pop($r);
$modelClass = $this->normalizeModelClass($tableName, $prefix);
echo "executing command: php yii gii/model --tableName={$tableName} --modelClass={$modelClass} --ns={$namespace} --overwrite=1 --interactive=0\n";
echo `php yii gii/model --tableName={$tableName} --modelClass={$modelClass} --ns={$namespace} --overwrite=1 --interactive=0`;
}
return ExitCode::OK;
}
/**
* 将数据表去掉前缀转为 模型的类名
* @param string $tableName
* @param string $prefix
* @return string
*/
private function normalizeModelClass(string $tableName, string $prefix=''): string
{
$trim = substr($tableName, strlen($prefix));
$normalized = str_replace('_', ' ', $trim);
$normalized = str_replace(' ', '', ucwords($normalized));
return $normalized;
}
}
使用方法:
将文件放置于 yii2 commands 目录下面,执行 yii db-map/index {namespace} {table_prefix}
, 可通过 yii db-map/index --help
查看命令参数.