jmsfwk/fluent-phinx

Phinx 的 Laravel 风格迁移

0.4.0 2021-03-04 12:17 UTC

This package is auto-updated.

Last update: 2024-09-04 20:29:37 UTC


README

Phinx 提供 Laravel 风格的迁移。

简介

Phinx 提供了一种在迁移中声明模式的方法,但由于列类型选项众多,使用起来有些困难。

Fluent Phinx 提供了一个流畅的 Laravel 风格的模式构建器,以简化迁移的编写和读取。

迁移结构

Fluent Phinx 依赖于常规的 Phinx 迁移文件,使用 change 方法或 up/down 方法对。

可以使用 Fluent 特性向迁移文件添加流畅功能。

<?php

use jmsfwk\FluentPhinx\Fluent;
use jmsfwk\FluentPhinx\Schema\Blueprint;
use Phinx\Migration\AbstractMigration;

class CreateUsersTable extends AbstractMigration
{
    use Fluent;

    public function change()
    {
        $this->create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            
            $table->id = false; // Turn off automatic id column
            $table->primary_key = 'id'; // Set the 'id' column as the primary key
        });
    }
}

表格

创建表格

要创建新的数据库表格,请使用来自 Fluent 特性的 create 方法。创建方法接受两个参数:第一个是表格名称,第二个是接收一个 Blueprint 对象的闭包,该对象可以用来定义新的表格

$this->create('users', function (Blueprint $table) {
    $table->increments('id');
});

在创建表格时,可以使用模式构建器的任何列方法来定义表格的列。

更新表格

要更新表格,可以使用来自 Fluent 特性的 update 方法。与 create 方法类似,这也会接受两个参数:表格名称和一个接收 Blueprint 对象的闭包来定义更改。

$this->update('users', function (Blueprint $table) {
    $table->integer('votes');
});

表格选项

可以使用以下属性在模式构建器上定义表格的选项

索引

创建索引

索引可以在两个地方添加,从列定义和从 Blueprint 对象。

从列中,您可以传递索引名称到索引方法。

$table->string('email')->unique();

在定义列之后创建索引时,应该在模式构建器的蓝图上调用 unique 方法。此方法接受应接收唯一索引的列名称

$table->unique('email');

您可以传递列的数组到索引方法以创建一个复合(或组合)索引

$table->index(['account_id', 'created_at']);

在创建索引时,您可以传递第二个参数到方法以指定索引名称

$table->unique('email', 'unique_email');

可用的索引类型