可以使用迁移来创建动态表名吗?

时间:2015-07-04 06:05:35

标签: migration yii2 yii2-advanced-app

我想为每个用户创建一个新表。例如,当用户注册时,应创建名为'User-uniqueID'的表。这可以通过迁移来实现吗?或者我应该使用stored procedure吗?

1 个答案:

答案 0 :(得分:0)

是的我通常使用此方法创建dinamic表,如下所示(在这种情况下,我为用户区域/ land_scope_code创建一个表:

class m150420_221138_test extends Migration
{
    public function up()
    {


        $tableOptions = 'CHARACTER SET utf8 ENGINE=InnoDB';

        $modelUserParam = UserParam::findOne(['user_id'=> Yii::$app->user->id]);


        $tableName = '_yourTableName';

        $this->createTable( $modelUserParam->land_scope_code . $tableName, [
            yourfield,
                ....... 
            'id' =>  'pk', 
        ], $tableOptions);

    }

    public function down()
    {

        $modelUserParam = UserParam::findOne(['user_id'=> Yii::$app->user->id]);


        $tableName = '_yourTableName';

        $this->droptable(  $modelUserParam->land_scope_code. $tableName);
    }

    /*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */
}