在advanced\console\migrations文件夾下有一個 m130524_201442_init.php 文件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
<?php
use
yii\db\Schema;
use
yii\db\Migration;
class
m130524_201442_init
extends
Migration
{
public
function
up()
{
$tableOptions
= null;
if
(
$this
->db->driverName ===
'mysql'
) {
$tableOptions
=
'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB'
;
}
$this
->createTable(
'{{%user}}'
, [
'id'
=>
$this
->primaryKey(),
'username'
=>
$this
->string()->notNull()->unique(),
'auth_key'
=>
$this
->string(32)->notNull(),
'password_hash'
=>
$this
->string()->notNull(),
'password_reset_token'
=>
$this
->string()->unique(),
'email'
=>
$this
->string()->notNull()->unique(),
'status'
=>
$this
->smallInteger()->notNull()->defaultValue(10),
'created_at'
=>
$this
->integer()->notNull(),
'updated_at'
=>
$this
->integer()->notNull(),
],
$tableOptions
);
}
public
function
down()
{
$this
->dropTable(
'{{%user}}'
);
}
}
|
用cmd命令行進入advanced目錄 ( 該目錄下有yii.bat )
執行命令,選yes(輸入y)
1
|
yii migrate console/migrations/m130524_201442_init.php
|
這樣就在數據庫中新建了一張表user和另一張表migration
其中migration表的內容大致如下,猜想這個version字段和每次執行命令時php文件的名字&文件里的class名有關,所以每次執行命令時需要改動文件名和文件里面的class名
那么,現在新建一張blog表,包含id、title、content、create_time四個字段
-
先將該php文件復制備份, 再將該文件重命名為m330524_201442_init.php(隨機數字,只要和已有的version不同)
-
再將文件內的class m220524_201442_init extends Migration 中的 220524 改為 330524 (和文件名一樣)
-
編輯字段內容
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
<?php
use
yii\db\Schema;
use
yii\db\Migration;
class
m220524_201442_init
extends
Migration
{
public
function
up()
{
$tableOptions
= null;
if
(
$this
->db->driverName ===
'mysql'
) {
$tableOptions
=
'CHARACTER SET utf8 COLLATE utf8_general_ci ENGINE=InnoDB COMMENT="文章表"'
;
}
$this
->createTable(
'blog'
, [
'id'
=>
$this
->primaryKey(),
'title'
=>
$this
->string(100)->notNull()->defaultValue(
''
),
'content'
=>
$this
->text(),
'create_time'
=>
$this
->datetime(),
],
$tableOptions
);
}
public
function
down()
{
$this
->dropTable(
'blog'
);
}
}
|
最后執行命令,選yes
1
|
yii migrate console/migrations/m130524_201442_init.php
|
可以看到blog表建好了,隨機添加兩條數據無誤
==========2019.7.23添加============
哎我圖呢?......算了
如果要建一張新表
控制台先將路徑切換到advanced根目錄
yii migrate/create create_blog_table
輸入y,回車。會在advanced\console\migrations目錄下出現一個新文件m190723_023311_create_blog_table.php,其內容如下
<?php use yii\db\Migration; /** * Handles the creation of table `{{%blog}}`. */ class m190723_023311_create_blog_table extends Migration { /** * {@inheritdoc} */ public function safeUp() { $this->createTable('{{%blog}}', [ 'id' => $this->primaryKey(), ]); } /** * {@inheritdoc} */ public function safeDown() { $this->dropTable('{{%blog}}'); } }
目前只有ID自增,現隨便加幾個字段
public function safeUp() { $this->createTable('{{%blog}}', [ 'id' => $this->primaryKey(), 'title' => $this->string(100)->notNull()->defaultValue(''), 'content' => $this->text(), 'create_time' => $this->datetime(), ]); }
這就准備好了,再在控制台中輸入
yii migrate
輸入y,回車,則看到mysql里面會增加幾張表(migrations目錄下有幾個文件就新增幾張表),其中一張就是blog表