What is the best practice for Migration in Yii2?

Usually my migrations are like:

        $this->addColumn('{{%sku}}', 'substitute_1', $this->string(64)->null());

I am curious though why we are using table names with curly braces and percent signs. Can we just do the same like this:

        $this->addColumn(models\Sku::tableName(), 'substitute_1', $this->string(64)->null());

Any reasons not to do this for a data migration?

You can drop a percent sign if you don’t have a table prefix.

But I don’t understand why would you need to use that second option, if everything works fine. So I’d say the best practice is provided by developers, the first one.

Thanks @Tendy

I was just curious on what everyone was doing. Why do we need the curly braces? Just asking out of curiosity.

If there is some prefix configured on the db connection, the {{}} prefix it and you don’t have to type it everywhere. Then you need to change the prefix, you change in the connection setting and not in all the code.

Consider that your tables are named tbl_user, tbl_thing

in the connection the prefix is set to ‘tbl_’

then, in active records the value for tableName is {{user}}, {{thing}}


I don’t know how to put it well, but curly braces are for a correct SQL-command.

// executes this SQL for MySQL: SELECT COUNT(`id`) FROM `employee`
$count = Yii::$app->db->createCommand("SELECT COUNT([[id]]) FROM {{employee}}")->queryScalar();
1 Like

This is a bad idea, as migrations should be as independent from your code as possible.

In the future, if you delete the Sku for some reason, that migration will brake.