關於YII2 數據庫遷移(新建表)的批量處理(適合有表但是未做遷移文件,自動生成遷移文件)

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

運行成功

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章