Phinx使用记录

211 阅读1分钟

我正在参加「掘金·启航计划」

安装

进入你的项目根目录,我以tp6为例。

我的项目跟目录/Users/fgc/Sites/tp6

# 安装不成功的原因有很多

# 解决一下几个问题 应该可以安装成功
# 1. 切换为中国国内的镜像源
# composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/


composer require robmorgan/phinx

使用

安装成功以后就会在 /Users/你的电脑名字/Sites/tp6/vendor/robmorgan/phinx/bin目录下有phinx 可执行文件。 就说明安装成功了。

在tp6根目录下执行 sudo php vendor/bin/phinx init, 而不是在/Users/你的电脑名字/Sites/tp6/vendor/robmorgan/phinx/bin这个目录下执行 init。执行完成以后就会发现在根目录生成phinx.php文件。

执行 sudo php vendor/bin/phinx create MyNewMigration,就会在项目的根目录下创建db/migrations/XXXXXX.migration.php

注意,这个文件夹需要可读权限,可以把整个项目进行一个可读权限的设置

sudo chmod 777 ./tp6

修改migration文件执行数据库操作: 建立一张user

<?php
declare(strict_types=1);

use Phinx\Migration\AbstractMigration;

final class MyNewMigration extends AbstractMigration
{
    /**
     * Change Method.
     *
     * Write your reversible migrations using this method.
     *
     * More information on writing migrations is available here:
     * https://book.cakephp.org/phinx/0/en/migrations.html#the-change-method
     *
     * Remember to call "create()" or "update()" and NOT "save()" when working
     * with the Table class.
     */
    public function change(): void
    {
        $this->table('users')
            ->addColumn('name', 'string', ['limit' => 255])
            ->addColumn('email', 'string', ['limit' => 255])
            ->addColumn('password', 'string', ['limit' => 255])
            ->addColumn('created_at', 'datetime', ['default' => 'CURRENT_TIMESTAMP'])
            ->addColumn('updated_at', 'datetime', ['default' => 'CURRENT_TIMESTAMP'])
            ->create();
    }
}

执行 phinx migrate -e development , 在执行之前要修改配置文件。 配置文件是 phinx.php

'development' => [
  'adapter' => 'mysql',
  'host' => 'localhost',
  'name' => 'test',
  'user' => 'root',
  'pass' => 'root',
  'port' => '3306',
  'charset' => 'utf8mb4',
],

执行完migrate命令以后, 数据库中就会有相应的操作了。我们看到下图生产了两张表

使用到的命令行

  • php vendor/bin/phinx status

  • vendor/bin/phinx rollback -e development -t 20220707080903 -f

  • php vendor/bin/phinx create ChangeUserFieldEightMigration
  • php vendor/bin/phinx migrate -e development

在TP5中使用

使用composer require topthink/think-migration命令行安装

在改目录的终端执行 php think

创建迁移文件

执行 php think migrate:create AddTeacherAndCourse

注意:AddTeacherAndCourse是创建的迁移文件的名称,大写驼峰命名

以下是生成的迁移文件

往迁移文件写SQL语句

 public function change()
    {
        $sql = <<<SQL
insert into as_rule(type,pid,name,title,icon,`condition`,remark,ismenu,createtime,updatetime,weigh,status)
    value ('file',554,'performance/daily/recalc_performance','重新计算业绩','fa fa-circle-o','','',0,1572493185,1572493185,0,'normal')
SQL;
        $this->execute($sql);
    }