В Yii создание и поддержка структур БД осуществляется при помощи миграций. Управление миграциями производится через консольную команду yiic migrate, которая позволяет создать новую миграцию, применить, откатить и просмотреть истории миграций.
Для начала работы нам необходимо создать коннектор к mysql.
В зависимости от реализации делается это в файле config/main-local.php или ином.
'db' => [
'dsn' => 'mysql:host=localhost;dbname=tvh41',
'username' => 'root',
'password' => 'rootpasswd',
'tablePrefix' => 'tvh_',
], |
'db' => [
'dsn' => 'mysql:host=localhost;dbname=tvh41',
'username' => 'root',
'password' => 'rootpasswd',
'tablePrefix' => 'tvh_',
],
Запустим команду создания первой миграции:
php yii migrate/create create_organization_table |
php yii migrate/create create_organization_table
Yii Migration Tool (based on Yii v2.0.7-dev)
Create new migration '/home/spions/Web/yii2-app-basic/migrations/m151231_064302_create_organization_table.php'? (yes|no) [no]:yes
New migration created successfully. |
Yii Migration Tool (based on Yii v2.0.7-dev)
Create new migration '/home/spions/Web/yii2-app-basic/migrations/m151231_064302_create_organization_table.php'? (yes|no) [no]:yes
New migration created successfully.
Создаем структуру базы данных
По указанному пути (/home/spions/Web/yii2-app-basic/migrations/m151231_064302_create_organization_table.php) вносим необходимые данные для создание структуры базы данных:
<?php
use yii\db\Schema;
use yii\db\Migration;
class m151231_064302_create_organization_table extends Migration
{
public function up() {
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
$this->createTable('{{%organization}}', [
'id' => $this->primaryKey(),
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
'name' => $this->string()->notNull(),
'status' => $this->smallInteger()->notNull()->defaultValue(0),
], $tableOptions);
$this->createIndex('idx_org_name', '{{%organization}}', 'name');
$this->createIndex('idx_org_status', '{{%organization}}', 'status');
}
public function down()
{
echo "m151231_064302_create_organization_table cannot be reverted.\n";
//$this->dropTable('{{%organization}}');
return false;
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
} |
<?php
use yii\db\Schema;
use yii\db\Migration;
class m151231_064302_create_organization_table extends Migration
{
public function up() {
$tableOptions = null;
if ($this->db->driverName === 'mysql') {
$tableOptions = 'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB';
}
$this->createTable('{{%organization}}', [
'id' => $this->primaryKey(),
'created_at' => $this->integer()->notNull(),
'updated_at' => $this->integer()->notNull(),
'name' => $this->string()->notNull(),
'status' => $this->smallInteger()->notNull()->defaultValue(0),
], $tableOptions);
$this->createIndex('idx_org_name', '{{%organization}}', 'name');
$this->createIndex('idx_org_status', '{{%organization}}', 'status');
}
public function down()
{
echo "m151231_064302_create_organization_table cannot be reverted.\n";
//$this->dropTable('{{%organization}}');
return false;
}
/*
// Use safeUp/safeDown to run migration code within a transaction
public function safeUp()
{
}
public function safeDown()
{
}
*/
}
Создадим новую базу данных через консоль или phpMyAdmin и запустим миграцию на выполнение
mysql -uroot -p --execute='create database tvh41 character set utf8;' |
mysql -uroot -p --execute='create database tvh41 character set utf8;'
spions: ~/Web/yii2-app-basic $ php yii migrate/up
Yii Migration Tool (based on Yii v2.0.7-dev)
Creating migration history table "migration"...Done.
Total 1 new migration to be applied:
m151231_064302_create_organization_table
Apply the above migration? (yes|no) [no]:yes
*** applying m151231_064302_create_organization_table
> create table {{%organization}} ... done (time: 0.037s)
> create index idx_org_name on {{%organization}} (name) ... done (time: 0.096s)
> create index idx_org_status on {{%organization}} (status) ... done (time: 0.063s)
*** applied m151231_064302_create_organization_table (time: 0.241s)
1 migration was applied.
Migrated up successfully. |
spions: ~/Web/yii2-app-basic $ php yii migrate/up
Yii Migration Tool (based on Yii v2.0.7-dev)
Creating migration history table "migration"...Done.
Total 1 new migration to be applied:
m151231_064302_create_organization_table
Apply the above migration? (yes|no) [no]:yes
*** applying m151231_064302_create_organization_table
> create table {{%organization}} ... done (time: 0.037s)
> create index idx_org_name on {{%organization}} (name) ... done (time: 0.096s)
> create index idx_org_status on {{%organization}} (status) ... done (time: 0.063s)
*** applied m151231_064302_create_organization_table (time: 0.241s)
1 migration was applied.
Migrated up successfully.
Проверяем успешность создания таблицы
$ mysql -uroot -p --execute='use tvh41; SHOW TABLES;'
Enter password:
+-----------------+
| Tables_in_tvh41 |
+-----------------+
| migration |
| organization |
+-----------------+ |
$ mysql -uroot -p --execute='use tvh41; SHOW TABLES;'
Enter password:
+-----------------+
| Tables_in_tvh41 |
+-----------------+
| migration |
| organization |
+-----------------+
Несмотря на обилие текста — новые таблицы делаются достаточно быстро, использование git для контроля версий, позволяет всей команде актуализировать изменения не только кода, но и БД.
Материал для ознакомления: Yii2 Миграции