yii2自动生成数据库表migrations

yii2使用代码自动生成数据库表对应migrations

1.首先配置db数据库,例:



return [
    'class' => 'yii\db\Connection',
    'dsn' => 'mysql:host=localhost;dbname=dbname',
    'username' => '',
    'password' => '',
    'charset' => 'utf8mb4',
];

2.选择能访问到的类,添加代码:

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 = 'm191210_0'.$num.'_create_'.$item['table_name'].'.php';
            $myfile = fopen($str, "w") or die("Unable to open file!");
            $txt = ".'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');
    }

最后运行该方法接口,输出“success”,检查web下生成了多个migrations文件,可以配置生成路径到mirations目录下,也可以生成后复制到migrations目录下,方便使用数据库转移。

你可能感兴趣的:(Yii2,php)