Databases 10 min read

Mastering ThinkPHP 5.1 Database Migrations: Create, Run, and Manage Schemas

This guide explains what database migrations are, why they simplify schema changes in team projects, and provides step‑by‑step instructions for installing, creating, customizing, and executing ThinkPHP 5.1 migrations using the CLI commands and example code.

Open Source Tech Hub
Open Source Tech Hub
Open Source Tech Hub
Mastering ThinkPHP 5.1 Database Migrations: Create, Run, and Manage Schemas

What Is a Migration?

In the context of PHP, a migration is a set of abstracted SQL files that manage database schema changes. Instead of writing raw SQL and manually applying it on each developer’s machine, migrations allow version‑controlled, repeatable updates.

Purpose of Migration Files

Migration files encapsulate operations such as creating tables, adding or removing columns, and dropping tables. They provide a declarative way to modify the database without writing raw SQL each time.

Migrate Command Overview

migrate:breakpoint

– Manage breakpoints. migrate:create – Generate a new migration file. migrate:rollback – Roll back the last or a specific migration. migrate:run – Apply pending migrations. migrate:status – Show the current migration status.

Using Migration in ThinkPHP 5.1

ThinkPHP 5 provides a migration solution, but it must be installed manually.

composer require topthink/think-migration v2.0.3
For ThinkPHP 6 the package is installed by default; the command above forces the TP5.1 version (v2.0.3). More versions are listed at https://packagist.org/packages/topthink/think-migration.

Verify the installation with:

php think

Create Command

Syntax: php think migrate:create TableName Replace TableName with a Pascal‑Case name, e.g., Video:

# 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

The migration file is stored under database/migrations. File naming follows the pattern timestamp_randomNumber_filename.php.

Example: 20190804032741_video.php

Sample content of the generated file:

<?php
use think\migration\Migrator;
use think\migration\db\Column;

class Video extends Migrator
{
    public function change()
    {
        // Write reversible migration commands here.
    }
}

Adding Fields with up() / down()

Replace the default change method with explicit up (apply) and down (rollback) methods.

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();
}
public function down()
{
    $this->dropTable('video');
}

Run Command

After creating the migration, execute it with: php think migrate:run Two tables are created: iot_migrations (records migration history) and iot_video (the actual data table). The iot_video schema looks like:

+----------+-------------+------+-----+---------+----------------+
| 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    |                |
+----------+-------------+------+-----+---------+----------------+

Note: ThinkPHP automatically adds an id primary key if the column name is id, so you do not need to define it manually.

Status Command

# 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

This table lists each migration’s execution state, timestamps, and name.

Breakpoint Command Example

The breakpoint command can be used together with Redis event subscriptions. Below is a minimal example of a Redis subscriber that could be triggered during a migration breakpoint:

class RedisSubscribe
{
    public function subscribe()
    {
        $redis = BaseRedis::plocal();
        $redis->setOption(\Redis::OPT_READ_TIMEOUT, -1);
        $redis->psubscribe(['__keyevent@1__:expired'], function ($redis, $pattern, $chan, $msg) {
            Log::info('[订阅事件] 过期KEY ' . $msg);
            $originData = explode(':', $msg);
            $event_key = $originData[1] ?? '0';
            $event_status = $originData[0] ?? '0';
            // Process the event based on type.
        });
    }
}

In this snippet, $msg represents a Redis key such as S20190722100001:1001, where the prefix encodes the order number and the suffix encodes the event type (e.g., order expiration).

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

migrationCLIPHPThinkPHP
Open Source Tech Hub
Written by

Open Source Tech Hub

Sharing cutting-edge internet technologies and practical AI resources.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.