11

yii2自动生成数据库表migrations - 包子啥汤

 3 years ago
source link: https://www.deaboway.com/yii2-auto-create-database-tables-migrations.html#.X-EgSxMRWo8
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

yii2自动生成数据库表migrations

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

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

<?php

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

2.在console下面实现脚本:

<?php

namespace console\controllers;

use Yii;
use yii\console\Controller;
use scotthuangzl\export2excel\Export2ExcelBehavior;


class ToolsController extends Controller
{
	public function actionIndex()
	{
        //时间戳
        $now = time();
        echo "\ndate:".date("Y-m-d H:i:s")."\n";
    }


    public function actionMig()
    {
        $model = \Yii::$app->db->createCommand("select table_name from information_schema.tables where table_schema='letsbook' and table_type='base table'");
        $posts = $model->queryAll();

        $str = 'm200610_110612_create_all_tables.php';
        $myfile = fopen($str, "w") or die("Unable to open file!");
        $txt = "<?php
            use yii\db\Migration;
 
            class m200610_110612_create_all_tables extends Migration
            {
                public function safeUp()
                {
            ";

        // create tables
        foreach ($posts as  $key => $item) {
            $sql = "show create table ".$item['table_name']." ";
            $keys = \Yii::$app->db->createCommand($sql);
            $keyposts = $keys->queryOne();
            $txt .= '$this->execute('."         \"".$keyposts['Create Table']."\");
            ";
        }

        $txt .= "}
                public function safeDown()
                {
                ";

        // drop tables
        foreach ($posts as  $key => $item) {
            $txt .=  '$this->dropTable('."'".$item['table_name']."');
            ";
        }

        $txt .= "
                }
            }
            ?>";
        fwrite($myfile, $txt);
        fclose($myfile);
        print_r('success');
    }
}

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

欢迎关注我的微信公众号:

qrcwechat.jpg

如无特殊说明,文章均为本站原创,转载请注明出处!


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK