php迁移工具phoenix的用法
安装
composer require lulco/phoenix
composer require fakerphp/faker
配置
创建目录
参考的各大框架都是这样弄的 m代表migrations s代表seeds。
创建配置文件
<?php
return [
'migration_dirs' => [
'm' => __DIR__ . '/database/m',
's' => __DIR__ . '/database/s',
],
'environments' => [
'local' => [
'adapter' => 'mysql',
'host' => 'localhost',
'port' => 3306, // optional
'username' => 'root',
'password' => 'root',
'db_name' => 'blog',
'charset' => 'utf8mb4',
],
'production' => [
'adapter' => 'mysql',
'host' => 'production_host',
'port' => 3306, // optional
'username' => 'user',
'password' => 'pass',
'db_name' => 'blog',
'charset' => 'utf8mb4',
],
],
'default_environment' => 'local',
'log_table_name' => 'phoenix_log',
];
执行迁移文档指定目录
php vendor/bin/phoenix migrate -c config/phoenix.php -e develop
创建迁移文件
php vendor/bin/phoenix create Approval -c config/phoenix.php
推荐用原生sql创建数据库
<?php
use Phoenix\Migration\AbstractMigration;
class User extends AbstractMigration
{
protected function up(): void
{
$this->execute(
"create table lu_user
(
id int not null auto_increment primary key,
username varchar(10) comment '用户名',
password varchar(32) comment '密码',
phone varchar(11) comment '注册手机号',
email varchar(50) unique comment '邮箱',
last_login_ip char (15) comment '最后登录IP地址',
last_login_time timestamp null comment '最后登录的时间',
active tinyint not null default 0 comment '激活状态 0:未激活 1:激活',
create_time timestamp null comment '创建时间',
update_time timestamp null comment '更新时间',
delete_time timestamp null comment '删除时间'
);"
);
}
protected function down(): void
{
$this->execute(
"drop table lu_user;"
);
}
}
执行迁移
php vendor/bin/phoenix migrate --dir m
回退
php vendor/bin/phoenix rollback --dir m
填充
由于lulco/phoenix
这个包是没有这个功能的,但是其实填充也是可以当作一个普通的迁移文件来执行的,所以创建迁移文件的时候,我们可以单独创建
UserSeeder
来当作填充文件,存放的目录我们放在s目录
php vendor\bin\phoenix create UserSeeder s
<?php
use Phoenix\Migration\AbstractMigration;
class UserSeeder extends AbstractMigration
{
protected function up(): void
{
$faker = Faker\Factory::create('zh_CN');
$data = [];
for ($i = 0; $i < 100; $i++) {
$data[] = [
'username' => $faker->randomLetter . $faker->unique()->randomNumber(5, true),
'password' => $faker->password,
'phone' => $faker->phoneNumber,
'email' => $faker->email,
'last_login_ip' => $faker->ipv4,
'last_login_time' => date('Y-m-d H:i:s'),
'active' => [0, 1][rand(0, 1)],
'create_time' => date('Y-m-d H:i:s'),
'update_time' => date('Y-m-d H:i:s'),
'delete_time' => date('Y-m-d H:i:s'),
];
}
//清空表
$this->table('lu_user')->truncate();
//插入数据
$this->insert('lu_user',$data);
//更新数据,方便我们测试
$this->update('lu_user',['username'=>'admin','password'=>'admin123'],['id'=>1]);
}
protected function down(): void
{
$this->table('lu_user')->truncate();
}
}
执行整个s目录进行填充
php vendor/bin/phoenix migrate --dir s
单独执行某个文件
php vendor/bin/phoenix migrate --class UserSeeder