yii2自动生成数据库表migrations

3 篇文章 0 订阅

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

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

<?php

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 = "<?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');
    }

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

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值