PHP Series | ThinkPHP5 migration database migration tool

For more, please pay attention to micro-channel public number

ThinkPHP5 migration database migration tool

What is Migration?

migration with Google translate meaning immigrants, in PHP we will understand it as migration, the Migration used in the database can be understood as database migration strategy. Before and after the migration and development, we are all hand-written SQL statements to create the table, you need to manually create success in the implementation of the database, create a project database initialization light to spend a lot of time.

Also in the multiplayer team development, if required every developer used in the local database so we are usually back up database files into SQL pass each other, that's not very complicated, tedious that if the database field to a table changes occur then we need to change the SQL statement passed to each partner to develop small so that they are in the local manual updates, so you can once, but many times it? I think the development team in this kind of thing is certainly a headache slightly, so the migration was born slightly.

Migration is that some file management database structure, these files are actually abstract of SQL, can be changed by command line structure of the database, these files are stored in the project, as the project version of iterations and iteration.

During development, if a small partner changes the structure of the database table, she only needs to generate a migration file and pushed to the version control system, such as: Git, and notify other small partners, other small partners only need to pull and then command line under migration command on it, simplifies the traditional process of changes in the database, to speed up the development of the project.

Migration file action

The main role of migration file is used to manage the structure of the database, in fact, it is a set of SQL statements abstraction, file migration can create a table, drop table, add a field, delete the field, and so basically all database operations, which in fact like you manually write SQL statement, but you do not need in the migration manually write SQL statements, only in accordance with its rules of syntax to invoke it to be all right.

migrate Commands

  • migrate:breakpoint Manage breakpoints

  • migrate:create Create a migration file

  • migrate:rollback The last rollback or specific migration
  • migrate:run Database migration
  • migrate:status Migration status

Thinkphp5.1 use migration

thinkphp5 provides a set of migration solutions for developers, but by default migration is not installed, we need to be installed manually. Change the working directory to tp5 projects under execution:

composer require topthink/think-migration v2.0.3

TP6 default version installed, here designated installation tp5.1 version is V2.0.3, more versions address: https://packagist.org/packages/topthink/think-migration

Execute php thinkcommand to see if the installation was successful

images

We can see the migration and seed from the figure, the installation was successful

create command

Syntax:php think migrate:create TableName

TableNameFormat: uppercase first letter hump law. This command is used to create a migration file, such as where we create a Videothe migration file:

php think migrate:create Video

First performance Migraton it will prompt some of the information, all unified yes here can be friends. Successfully created as follows:

# php think migrate:create Video
PHP Warning:  Module 'redis' already loaded in Unknown on line 0
 Create migrations directory? [y]/n (yes/no) [yes]:
 > yes

created ./database/migrations/20190804032741_video.php

More than in the root directory of the project a database directory, there is a migration folder, the folder is used to store the migration file, open the can see the Video of the migration file we just created:

images

File format naming convention:时间 + 随机数 + _ + 文件名

After the file is created, look at its contents:

<?php

use think\migration\Migrator;
use think\migration\db\Column;

class Video extends Migrator
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * http://docs.phinx.org/en/latest/migrations.html#the-abstractmigration-class
     *
     * The following commands can be used in this method and Phinx will
     * automatically reverse them when rolling back:
     *
     *    createTable
     *    renameTable
     *    addColumn
     *    renameColumn
     *    addIndex
     *    addForeignKey
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change()
    {

    }
}

Here I need to give my Video files created above to increase the field

Video The following table structure

Field Types of Explanation
id int Primary key
nickname varchar(16) Video name
email varchar(32) mailbox
password varchar64) password

Remove the default built-in  change method to create  up() methods and  down() methods. up() The method of execution is the  run command to be executed, down() in executing  rollback the command execution.

up() Methods as below :

public function up()
{
    $table = $this->table('video');
    $table->addColumn('name', 'string', ['limit' => 16, 'null' => false,'comment'=>'视频名称'])
    ->addColumn('email', 'string', ['limit' => 32, 'null' => false,'comment'=>'邮箱'])
    ->addColumn('password', 'string', ['limit' => 64, 'null' => false,'comment'=>'密码'])
    ->create();
}

down() Methods as below:

public function down()
{
    $this->dropTable('video');
}

The entire contents of the file

<?php

use think\migration\Migrator;
use think\migration\db\Column;

class Video extends Migrator
{
    // migrate:run 时执行
    public function up()
    {
        $table = $this->table('video');
        $table->addColumn('name', 'string', ['limit' => 16, 'null' => false,'comment'=>'名称'])
          ->addColumn('email', 'string', ['limit' => 32, 'null' => false,'comment'=>'邮箱'])
          ->addColumn('password', 'string', ['limit' => 64, 'null' => false,'comment'=>'密码'])
          ->create();
    }

    // migrate:rollback 时执行
    public function down()
    {
        $this->dropTable('video');
    }
}

In this way, you can create a video file migration on the table is created, the next step to learn the next command.

migrate: run the command

migration file is created, you need to perform  run the command can modify the database:

Note Before performing this procedure correctly configured  config/database.php . In here there is a database prefix iot_.

php think migrate:run

After successful execution, view the database, more than two tables iot_migrationsandiot_video

iot_videoThe following table structure

mysql> desc iot_video;
+----------+-------------+------+-----+---------+----------------+
| Field    | Type        | Null | Key | Default | Extra          |
+----------+-------------+------+-----+---------+----------------+
| id       | int(11)     | NO   | PRI | NULL    | auto_increment |
| name     | varchar(16) | NO   |     | NULL    |                |
| email    | varchar(32) | NO   |     | NULL    |                |
| password | varchar(64) | NO   |     | NULL    |                |
+----------+-------------+------+-----+---------+----------------+
4 rows in set (0.07 sec)

Before I define migration only specified nickname, email, passwordthree fields, but the execution runtable command to create the four fields, more than a idprimary key? This is thinkphp5adding to our default! Junior partner attention to it! If your primary key field called iddo not need to manually specifies.

iot_videoDesign table structure view comments

images

iot_migrationsWhat is the table of contents?

mysql> select * from iot_migrations G;
+----------------+----------------+---------------------+---------------------+------------+
| version        | migration_name | start_time          | end_time            | breakpoint |
+----------------+----------------+---------------------+---------------------+------------+
| 20190804032741 | Video          | 2019-08-04 11:49:49 | 2019-08-04 11:49:50 |          0 |
+----------------+----------------+---------------------+---------------------+------------+
1 row in set (0.08 sec)

It can be seen that just executed a record named after the run is successful, the file name and version 20,190,804,032,741 is one to one

migrate: status command

Description: displays the migration status

# php think migrate:status
 Status  Migration ID    Started              Finished             Migration Name 
----------------------------------------------------------------------------------
     up  20190804032741  2019-08-04 11:49:49  2019-08-04 11:49:50  Video

Form of a list showing the implementation of the migration of

migrate: roolback command

Description: Rollback last or specific migration

grammar:php think migrate:rollback

# php think migrate:rollback --help
Help:
 The migrate:rollback command reverts the last migration, or optionally up to a specific version

 php console migrate:rollback
 php console migrate:rollback -t 20111018185412 //指定版本
 php console migrate:rollback -d 20111018
 php console migrate:rollback -v

Rollback operation

# php think migrate:rollback
PHP Warning:  Module 'redis' already loaded in Unknown on line 0

 == 20190804032741 Video: reverting
 == 20190804032741 Video: reverted 0.1992s

All Done. Took 0.6151s

This time view the database table structure and database tables has been removed, it does not exist

mysql> desc iot_video;
1146 - Table 'iot.tinywan.com.iot_video' doesn't exist
mysql> select * from iot_migrations;
Empty set

Iot_migrations data in the table does not exist, along with deleted

New Field

Secondary operations on the table can not be edited twice in the same script, you can only create a new script.

The following table to iot_videoadd a new field, to regenerate the table structure

Video Table increase the field below

Field Types of Explanation
upload_time int(11) Upload time
user_id int(11) Upload User ID

Create a new script

# php think migrate:create Video2
created ./database/migrations/20190804082737_video2.php

Video2 file contents

<?php

use think\migration\Migrator;

class Video2 extends Migrator
{
    public function up()
    {
        $table = $this->table('video');
        $table->addColumn('upload_time', 'string', ['limit' => 11, 'null' => false,'comment'=>'上传时间'])
            ->addColumn('user_id', 'string', ['limit' => 11, 'null' => false,'comment'=>'上传用户ID'])
            ->save();
    }
}

data migration

# php think migrate:run

 == 20190804082737 Video2: migrating
 == 20190804082737 Video2: migrated 0.3345s

All Done. Took 0.7070s

View table structure

mysql> desc iot_video;
+-------------+-------------+------+-----+---------+----------------+
| Field       | Type        | Null | Key | Default | Extra          |
+-------------+-------------+------+-----+---------+----------------+
| id          | int(11)     | NO   | PRI | NULL    | auto_increment |
| name        | varchar(16) | NO   |     | NULL    |                |
| email       | varchar(32) | NO   |     | NULL    |                |
| password    | varchar(64) | NO   |     | NULL    |                |
| upload_time | varchar(11) | NO   |     | NULL    |                |
| user_id     | varchar(11) | NO   |     | NULL    |                |
+-------------+-------------+------+-----+---------+----------------+
6 rows in set (0.08 sec)

appendix

The method table

Method name description
setId(string $id) Set the primary key field name
setPrimaryKey (string $ key) Set the primary key
setEngine (string $ engine) Set storage engine, there are: InnoDB, MyISAM
setComment(string $comment) Setting table Notes
addTimestamps ($ createAtName String, String \ (updateAtName) | table plus the time to create and edit time two fields, the default field name is: create_time, update_time | | addColumn (\) columnName, $ of the type, \ (Options) | to table add a field | | changeColumn (\) columnName, $ newType, \ (Options) | attributes of a field change table | | create () | create a table | | save () | save table | | rename (\) newTableName) Rename the table name
hasTable($tableName) | exists() Determine whether there is table
setIndexes(array $indexs) Batch Set Index
drop() Deletes the current table
setForeignKeys(array \(foreignKeys) | 设置外键 | | removeColumn(\)columnName) Delete field
renameColumn($oldName, $newName) Rename the field
insert(array $data) Insert data

Column Type

Types of
biginteger
binary
boolean
date
datetime
decimal
float
integer
string
text
time
timestamp
uuid

Optional parameters

parameter Explanation
limit Length limit, integer
length With limitinteger
default The default value, mixed
null Whether empty, bool
after After which field
comment Note

Here it is for the decimal type:

parameter Explanation
precision Length, an integer
scale Length decimal, integer
signed Whether unsigned, bool

The following is for enum and set types:

parameter Explanation
values Defaults

Guess you like

Origin www.cnblogs.com/tinywan/p/11298997.html