在ThinkPHP框架中使用Phinx迁移工具,需要进行以下步骤:
安装Phinx依赖库:composer require robmorgan/phinx
配置Phinx:在项目根目录下创建phinx.php
文件,并添加以下内容:
<?php
return [
'paths' => [
'migrations' => 'database/migrations',
'seeds' => 'database/seeds'
],
'environments' => [
'default_migration_table' => 'phinxlog',
'default_database' => 'development',
'development' => [
'adapter' => 'mysql',
'host' => 'localhost',
'name' => 'database_name',
'user' => 'username',
'pass' => 'password',
'port' => '3306',
'charset' => 'utf8mb4',
],
]
];
其中,paths
指定迁移文件和数据填充文件的存放路径,environments
指定数据库连接信息。
创建迁移文件:使用命令vendor/bin/phinx create MigrationName
创建迁移文件,例如vendor/bin/phinx create CreateUserTable
。
编写迁移代码:在创建的迁移文件中编写up
和down
方法,分别表示升级和降级数据库的操作。
<?php
use think\migration\Migrator;
use think\migration\db\Column;
class CreateUserTable extends Migrator
{
public function up()
{
$table = $this->table('user');
$table->addColumn('username', 'string', ['limit' => 100])
->addColumn('password', 'string', ['limit' => 100])
->addColumn('email', 'string', ['limit' => 100])
->addColumn('created_at', 'datetime')
->addColumn('updated_at', 'datetime', ['null' => true])
->create();
}
public function down()
{
$this->dropTable('user');
}
}
在上面的例子中,使用了ThinkPHP内置的Migrator
类和Column
类来创建表和列。
vendor/bin/phinx migrate
来运行迁移。在运行迁移之前,需要在数据库中创建一个名为phinxlog
的表来记录迁移历史,可以使用以下命令来创建该表:
CREATE TABLE `phinxlog` (
`version` bigint(20) NOT NULL,
`migration_name` varchar(100) NOT NULL,
`start_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`end_time` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
`breakpoint` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`version`,`migration_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
vendor/bin/phinx rollback
来回滚迁移。需要注意的是,回滚操作只能回滚上一次迁移,如果需要回滚多次迁移,可以使用命令vendor/bin/phinx rollback -t N
,其中N
为需要回滚的迁移次数。
以上就是在ThinkPHP框架中使用Phinx迁移工具的基本步骤。