| 代号 | migration_generate |
版本 | v1 |
| 分类 | 模块开发 | 输出格式 | 纯文本 |
| 类型 | 系统模板 | ||
根据实体字段定义生成 Yii2 数据库迁移文件
原始模板内容
展开
# 任务:为"{{metamodelName}}"生成数据库迁移文件
## 背景信息
- 实体名称:{{metamodelName}}
- 实体代号:{{metamodelCode}}
- 所属模块:{{moduleName}}({{moduleCode}})
- 数据库表:{{tableName}}
- 主键字段:{{primaryKey}}
## 字段定义
{{fieldJson}}
## 外键信息
{{foreignSummary}}
## 迁移规范
请生成 Yii2 Migration 文件,遵循以下规范:
### 文件命名
`m{YYMMDD}_{HHMMSS}_create_{{metamodelCode}}_table.php`
### 标准结构
```php
public function safeUp()
{
$this->createTable('{{tableName}}', [
'{{primaryKey}}' => $this->char(32)->notNull(),
// ... 业务字段 ...
'share' => $this->char(1)->defaultValue('0'),
'remarks' => $this->text(),
'deleted' => $this->char(1)->defaultValue('0'),
'createdBy' => $this->string(32),
'createdDate' => $this->dateTime(),
'editedBy' => $this->string(32),
'editedDate' => $this->dateTime(),
'PRIMARY KEY ({{primaryKey}})',
], 'ENGINE=InnoDB DEFAULT CHARSET=utf8mb4');
// 索引
$this->createIndex('idx_{{metamodelCode}}_deleted', '{{tableName}}', 'deleted');
}
public function safeDown()
{
$this->dropTable('{{tableName}}');
}
```
### 类型映射
- VARCHAR → `$this->string(长度)`
- CHAR → `$this->char(长度)`
- INT → `$this->integer()`
- DECIMAL → `$this->decimal(总长, 小数位)`
- TEXT → `$this->text()`
- DATETIME → `$this->dateTime()`
- DATE → `$this->date()`
### 注意事项
1. 必须同时实现 `safeUp()` 和 `safeDown()`(可回滚)
2. 主键用 `CHAR(32)`(UUID),不用自增
3. 必须包含标准审计字段
4. 为常用查询字段添加索引
5. 外键字段建议添加索引但不添加外键约束
6. 迁移文件放在 `console/migrations/` 目录
7. 执行命令:`php console/tools/yii migrate`