Databases 6 min read

Using Phinx for Database Migrations in ThinkPHP

This tutorial explains how to install, configure, and operate Phinx within a ThinkPHP project to manage database schema migrations, create and run seed data, update tables, roll back changes, and keep development environments synchronized.

Laravel Tech Community
Laravel Tech Community
Laravel Tech Community
Using Phinx for Database Migrations in ThinkPHP

This guide demonstrates how to install and use Phinx in a ThinkPHP project for managing database schema and seed data.

1. Installation composer require nhzex/think-phinx 2. Initialization php vendor/bin/phinx init Running the above command generates a default phinx.php configuration file; alternatively you can create a custom PHP config file.

3. Configuration example

<?php
$config = array(
    'DB_HOST' => 'localhost',
    'DB_NAME' => 'root',
    'DB_USER' => 'root',
    'DB_PWD'  => ''
);
$settings = $config;

return array(
    "paths" => array(
        "migrations" => "db/migrations",
        "seeds"      => "db/seeds"
    ),
    "environments" => array(
        "defaut_migration_table" => "phinxlog",
        "default_database"       => "lleg",
        "default_environment"    => "development",
        "production" => array(
            "adapter" => "mysql",
            "host"    => $settings["DB_HOST"],
            "name"    => $settings["DB_NAME"],
            "user"    => $settings["DB_USER"],
            "pass"    => $settings["DB_PWD"],
            "port"    => 3306,
            "charset" => "utf8"
        ),
        "development" => array(
            "adapter" => "mysql",
            "host"    => $settings["DB_HOST"],
            "name"    => $settings["DB_NAME"],
            "user"    => $settings["DB_USER"],
            "pass"    => $settings["DB_PWD"],
            "port"    => 3306,
            "charset" => "utf8"
        )
    )
);

4. Basic commands php vendor/bin/phinx status – check connection status. php vendor/bin/phinx create Migration – generate a new migration file. php vendor/bin/phinx migrate – apply pending migrations.

After creating a migration, edit the generated file (e.g., 20180310020523_migration.php) and add column definitions:

public function change() {
    $user = $this->table('user');
    $user->addColumn('open_id', 'string', ['limit'=>64]);
    $user->addColumn('register_time', 'timestamp', ['default' => 'CURRENT_TIMESTAMP']);
    $user->addColumn('favorite_music', 'integer', ['default'=>0, 'comment'=>'喜欢的音乐']);
    $user->addColumn('favorite_vedio', 'integer', ['default'=>0, 'comment'=>'喜欢的视频数']);
    $user->addColumn('favorite_article', 'integer', ['default'=>0, 'comment'=>'喜欢的文章数']);
    $user->addColumn('baby_birthday', 'date', ['null'=>true, 'comment'=>'宝宝生日']);
    $user->addColumn('baby_sex', 'boolean', ['null'=>true, 'comment'=>'宝宝性别']);
    $user->addColumn('last_login', 'datetime', ['null'=>true, 'comment'=>'最后登陆日期']);
    $user->save();
}

Phinx automatically adds an auto‑increment primary key to each table.

5. Seeding data php vendor/bin/phinx seed:create CategorySeeder – creates CategorySeeder.php.

Edit the seeder to insert data, then run: php vendor/bin/phinx seed:run – executes all seeds.

To run a specific seed, use the -s option, e.g., php vendor/bin/phinx seed:run -s CategorySeeder.

6. Updating table structure

When a schema change is needed, create a new migration: php vendor/bin/phinx create ChangeArtist Edit its change method, for example:

public function change() {
    $this->execute('alter table resource drop column artist;');
    $resource = $this->table('resource');
    $resource->addColumn('artist', 'string', ['limit'=>128, 'default'=>'']);
    $resource->update();
}

Then run php vendor/bin/phinx migrate; only the new changes are applied.

7. Rollback php vendor/bin/phinx rollback – reverts the last migration batch.

8. Additional seeding example

php vendor/bin/phinx seed:create UserSeeder
php vendor/bin/phinx seed:run -e product

The generated seeder may look like:

<?php
use Phinx\Seed\AbstractSeed;

class UserSeeder extends AbstractSeed {
    public function run() {
        $data = array(
            array('id' => 1),
            array('id' => 2)
        );
        $posts = $this->table('users');
        $posts->insert($data)->save();
    }
}

Phinx is especially useful for synchronizing schema and seed data across development, testing, and production environments, ensuring consistent database structures and reducing manual errors.

The default_migration_table (default phinxlog) records applied migrations, preventing duplicate execution.

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.

CLISQLPHPdatabase migrationThinkPHPPhinx
Laravel Tech Community
Written by

Laravel Tech Community

Specializing in Laravel development, we continuously publish fresh content and grow alongside the elegant, stable Laravel framework.

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.