近期完成yii2数据库迁移,新建数据表。本地上已经有全部表,现在有自动生成数据库迁移文件
yii migrate/create create_table_name
生成:2019...._..._create_table_name.php
这里前面的是时间_时间戳
这里新建数据表是在safeup中用
$this->execute($sql);
思路:
寻找所有表的create 的命令,遍历生成对应的2019...._..._create_table_name.php文件
做法:
public function actionDown()
{
$model = Yii::$app->db->createCommand("select table_name from information_schema.tables where table_schema='数据库名称' and table_type='base table'");
$posts = $model->queryAll();
foreach ($posts as $key => $item) {
$sql = "show create table ".$item['table_name']." ";
$keys = Yii::$app->db->createCommand($sql);
$keyposts = $keys->queryOne();
$num =(string)(52200+$key);
$str = 'm190310_0'.$num.'_create_'.$item['table_name'].'.php';
$myfile = fopen($str, "w") or die("Unable to open file!");
$txt = "<?php
use yii\db\Migration;
class ".'m190310_0'.$num.'_create_'.$item['table_name']." extends Migration
{
public function safeUp()
{
".'$this->execute('."\"".$keyposts['Create Table']."\");
}
public function safeDown()
{
". '$this->dropTable('."'".$item['table_name']."');
}
}
";
fwrite($myfile, $txt);
fclose($myfile);
}
print_r('success');
}
即在web文件夹中新建了一堆2019...._..._create_table_name.php,这时我们只需要进行复制粘贴到migrations文件夹里,
讲数据库改成想要迁移的数据库
运行
yii migrate
运行成功