Why oh why is the standard of Yii2 documentation apparently so universally poor?
While trying to look into getting migrations going on my Yii development site I stumbled over a web page that appeared to lay things out pretty well. I should have guessed that life was not going to be that simple! This …
First we need to create a migration: yii create/migration insert_user
.. rapidly turned into an in depth investigation of the migration system. Try it yourself, the above command fails in at least two different ways.
First things first, what do migrations do in Yii? ‘Migration provides a set of convenient methods for manipulating database data and schema. For example, the insert() method can be used to easily insert a row of data into a database table; the createTable() method can be used to create a database table. Compared with the same methods in yii\db\Command, these methods will display extra information showing the method parameters and execution time, which may be useful when applying migrations.’
That comes from the Yii2 Documentation so at least there’s a start. When it is used with the command line it gives us a way to execute upgrade ( or downgrade ) code while inside the environment of our website.
We can use a Yii command to generate a framework migration file as follows.
Dream up a label for your migration and in the root directory of your Yii2 application issue the following command.
*> php yii migrate/create \migration_label/
The command responds with a prompt asking you to accept the generation of a new migration file. You’ll notice that the filename has some additional information concatenated in to it. Basically a time and date and key. These are used to track your use of migrations.
Some Gotcha’s and notes here.
- Migrations and other console commands use the console.php configuration. I spent a frustrating hour or three trying to work out why component configurations that I copied from the internet were apparently not working. I’d put them into web.php and not into console.php!
- When a migration file is run and it completes without error and entry is made into the table ‘migrations’ in your database along with a timestamp. If you are testing a migration subsequent edits of the migration file are not applied since the tool does not know that the file has changed. You need to either rename the file or simply drop the relative entry to the migration table before rerunning the migration.
While you are in your root directory issue the following command.
*> php yii help migrate
You’ll see some additional commands that give some more insight into the migrate system.
Next I’ll use a practical example of generating a migration to help with the installation of the Yii2 Authorization module to expand on how things work.