Command to migrate database to Yii 2.0

While learning Yii 2.0, I came across different ways to migrate my database. I usually follow from the yii 2 guide .

Using this tutorial, I am using commands like yii migrate / create migfile and yii migrate

Usually in my migration file up () , I would insert code like this:

$this->createTable('news', [
        'id' => Schema::TYPE_PK,
        'title' => Schema::TYPE_STRING . ' NOT NULL',
        'content' => Schema::TYPE_TEXT,
]);

      

However, I've also seen some tutorials like this one that uses a slightly different command and code in the migration file. From the second tutorial i used php yii migrate / create migfile

Whereas the syntax used in the up () method of the migration file was something like this:

return $this->createTable('posts', [
        'id' => 'INT PRIMARY KEY AUTO_INCREMENT',
        'title' => 'VARCHAR(255)',
        'content' => 'TEXT',

      

Now this has led to a lot of questions. 1. Is there any difference between php command yii and yii ? 2. What's the difference between using Schema :: and not using it? Is this the best approach when migrating a database, as this is what the Yii migration guide says, or is it just a matter of preference that can be used?

+3


source to share


1 answer


1) Usage yii

and php yii

exactly the same. If you look at the file yii

, you'll see it in the first line #!/usr/bin/env php

. This is called the "shebang" syntax and instructs your shell to automatically execute the yii

script using binary code php

. See: https://en.wikipedia.org/wiki/Shebang_%28Unix%29

2) The difference here is flexibility. If you use the syntax Schema::TYPE_PK

, Yii will automatically detect the exact column type based on your database database. For example, it Schema::TYPE_PK

translates to int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY

in MySQL, but if you use Postgres as your database, it will translate to serial NOT NULL PRIMARY KEY

. [1]



In practice, it is unlikely which method you are using because you are probably not going to switch to a different type of database halfway through your project, and therefore there is no need for your migration scripts to be database agnostic. Based on your preference, you can choose the syntax Schema

for added flexibility, or for a hard-coded syntax to make your hyphenation definitions more readable for future readers.

[1] See https://github.com/yiisoft/yii2/blob/master/framework/db/pgsql/QueryBuilder.php#L21 and https://github.com/yiisoft/yii2/blob/master/framework /db/mysql/QueryBuilder.php#L24

+5


source







All Articles