Reputation: 2221
While studying Yii 2.0, I've come across different ways people migrate their database. The first one, which I follow usually is from yii 2's guide.
Using this guide, I use commands such as yii migrate/create migrationfile and yii migrate
Normally inside my migration file up(), method I'd insert code like so:
$this->createTable('news', [
'id' => Schema::TYPE_PK,
'title' => Schema::TYPE_STRING . ' NOT NULL',
'content' => Schema::TYPE_TEXT,
]);
However, I've also seen some tutorials such as this one which uses a slightly different command and code in the migration file. From the second tutorial, I've used php yii migrate/create migrationfile
While the syntax used in the migration file up() method was something like so:
return $this->createTable('posts', [
'id' => 'INT PRIMARY KEY AUTO_INCREMENT',
'title' => 'VARCHAR(255)',
'content' => 'TEXT',
Now, this has resulted in number of questions. 1. Is there are difference between php yii and yii command? 2. What's the difference between using Schema:: vs not using it? Is it a better approach in migrating the database since it's what's written on Yii's guide to migrations or is it just a matter of preference which one to use?
Upvotes: 3
Views: 1311
Reputation: 491
1) Using yii
and php yii
is exactly the same. If you check out the yii
file, you'll see this on the first line: #!/usr/bin/env php
. This is called the "shebang" syntax, and instructs your shell to automatically execute the yii
script using the php
binary. See: https://en.wikipedia.org/wiki/Shebang_%28Unix%29
2) The difference here is flexibility. If you use the Schema::TYPE_PK
syntax, Yii will automatically determine the exact column type based on your database backend. For example, Schema::TYPE_PK
would translate to int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY
in MySQL, but if you'd use Postgres as database, it would translate to serial NOT NULL PRIMARY KEY
instead. [1]
In practice it's unlikely to make a difference which method you use, because you're probably not going to switch to a different type of database halfway through your project and thus there's no need for your migration scripts to be database-agnostic. Based on your preferences, you could opt for the Schema
syntax for the extra flexibility, or for the hardcoded syntax to make your migration definitions more clear to anyone reading them in the future.
[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
Upvotes: 6