近期完成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
運行成功