There is a project in which the user is registered. Upon successful registration, a separate mysql database with tables on the server is created for the user. As I deal with the Yii2 framework, it is not yet clear to me how to do this. At the moment I have 25 migrations for a new user database. But in order not to do this every time you register a user manually, I want to automate this process.

Question: with a successful user registration, I can find out the name of the new database. How to set up migrations so that knowing the database name rolls certain migrations there?

  • 2
    I’m pretty sure that you don’t really need to create a new database - etki
  • @Etki agree. unless of course there is a system for each new user, his own store, for example, a designer. where you can easily transfer databases to different servers. Well, all the same, I think this is not the case. - Naumov
  • crm rental system. - Mr. Music
  • @ Mr.Music, migration is a tool for convenient exchange of changes in the database between developers, and you just need to make manipulations with mysql, and make them where you usually do, in Controller'e in the Action , which you are responsible for registering the user . - MasterAlex

1 answer 1

If in the migration classes in the init() method there is no fixed specific base, then by calling the migrate command, you can specify the --db option in which you can point to the connection component to the required base.

For example: yii migrate --db=db2 — apply migrations to the db2 database.

This will not work if a specific database is specified in the init() method. For example:

 public function init() { $this->db = 'db3'; parent::init(); } 

In your case, as I understand it, you need to start the migration immediately after successful registration. How to start the migration command from the application read here: https://stackoverflow.com/questions/27983169/how-to-handle-yii2-migrations-on-hosts-without-console-access , and then: http: / /www.yiiframework.com/forum/index.php/topic/60000-run-migrate-command-in-a-function-in-yii2/ .

And here's what you need to do ( based on the fact that you have read the links given and what kind of code it is and where you already understand it ):

 new \yii\console\Application([ 'id' => 'Command runner', 'basePath' => '@app', 'components' => [ 'db' => ... /* тут нужно будет зарегистрировать компонент подключения к только что созданной базе данных. Зная ее имя, с этим не должно возникнуть трудностей */ ], ]);