yii命令行之migrate

2017-01-13 10:50:59来源:oschina作者:锟斤拷烫烫烫人点击

先不废话来贴几个例子,


创建表
yii migrate/create create_post --fields="author_id:integer:notNull:foreignKey(user),category_id:integer:defaultValue(1):foreignKey,title:string,body:text"

增加字段


yii migrate/create add_position_to_post --fields="position:integer"

以上代码均来自yii的权威指南,然而照样子试了下发现增加字段并没有像指南中说的那样成功,于是搬了源码出来看,发现指南中的说法是错误的。


源码路径vendor/yiisoft/yii2/console/controllers/MigrateController.php


中有这个方法用来自动生成migrate代码


protected function generateMigrationSourceCode($params)
{
$parsedFields = $this->parseFields();
$fields = $parsedFields['fields'];
$foreignKeys = $parsedFields['foreignKeys'];
$name = $params['name'];
$templateFile = $this->templateFile;
$table = null;
if (preg_match('/^create_junction(?:_table_for_|_for_|_)(.+)_and_(.+)_tables?$/', $name, $matches)) {
$templateFile = $this->generatorTemplateFiles['create_junction'];
$firstTable = mb_strtolower($matches[1], Yii::$app->charset);
$secondTable = mb_strtolower($matches[2], Yii::$app->charset);
$fields = array_merge(
[
[
'property' => $firstTable . '_id',
'decorators' => 'integer()',
],
[
'property' => $secondTable . '_id',
'decorators' => 'integer()',
],
],
$fields,
[
[
'property' => 'PRIMARY KEY(' .
$firstTable . '_id, ' .
$secondTable . '_id)',
],
]
);
$foreignKeys[$firstTable . '_id'] = $firstTable;
$foreignKeys[$secondTable . '_id'] = $secondTable;
$table = $firstTable . '_' . $secondTable;
} elseif (preg_match('/^add_(.+)_columns?_to_(.+)_table$/', $name, $matches)) {
$templateFile = $this->generatorTemplateFiles['add_column'];
$table = mb_strtolower($matches[2], Yii::$app->charset);
} elseif (preg_match('/^drop_(.+)_columns?_from_(.+)_table$/', $name, $matches)) {
$templateFile = $this->generatorTemplateFiles['drop_column'];
$table = mb_strtolower($matches[2], Yii::$app->charset);
} elseif (preg_match('/^create_(.+)_table$/', $name, $matches)) {
$this->addDefaultPrimaryKey($fields);
$templateFile = $this->generatorTemplateFiles['create_table'];
$table = mb_strtolower($matches[1], Yii::$app->charset);
} elseif (preg_match('/^drop_(.+)_table$/', $name, $matches)) {
$this->addDefaultPrimaryKey($fields);
$templateFile = $this->generatorTemplateFiles['drop_table'];
$table = mb_strtolower($matches[1], Yii::$app->charset);
}
foreach ($foreignKeys as $column => $relatedTable) {
$foreignKeys[$column] = [
'idx' => $this->generateTableName("idx-$table-$column"),
'fk' => $this->generateTableName("fk-$table-$column"),
'relatedTable' => $this->generateTableName($relatedTable),
];
}
return $this->renderFile(Yii::getAlias($templateFile), array_merge($params, [
'table' => $this->generateTableName($table),
'fields' => $fields,
'foreignKeys' => $foreignKeys,
]));
}

从中的正则中可以看出里面有“column”“table”之类的单词要匹配,于是将上面的命令改下:


yii migrate/create add_position_columns_to_post_table --fields="position:integer"


这样就成功了 注意正则的规则 应该是 add_列名_columns_to_表名_table,进行删除字段操作的时候也是类似的规则。在此备忘一下,不知道官方什么时候会改下指南的内容

最新文章

123

最新摄影

微信扫一扫

第七城市微信公众平台