ajcastro/fk-adder

让您快速添加外键!Laravel 迁移中的外键添加器。

v1.2.0 2019-04-11 06:35 UTC

README

让您智能且轻松地添加外键!适用于Laravel迁移的外键添加器。支持Laravel 4.25.*

FkAdder 的目的是简化迁移中外键列的声明。

FkAdder 为您做的事情
  • 记住外键的数据类型,并会为您自动提供正确的数据类型,因此您无需每次需要该特定外键时都回忆其数据类型。
  • 允许您以任意顺序创建迁移表。这解决了当您的表在参照表之前创建时的问题。通常这可能导致错误,如“引用表some_table不存在”,这发生在引用在迁移最后部分要迁移的表时。
  • 加快Laravel迁移开发速度。

安装

composer require ajcastro/fk-adder

别名

将别名添加到config/app.php文件中。您可以通过Laravel的自动发现功能跳过此步骤。

 'Fk' => FkAdder\Fk::class

配置

创建一个名为config/fk_adder.php的配置文件。

<?php

return [
    // For simple string-based declaration
    'fk_datatypes_path' => base_path('database/foreign_keys/fk_datatypes.php')
    // For class-based declaration, used for special cases and more control. You don't need this for simple cases .
    'fk_namespace' => 'Your\Fk\Namespace',
];

设置

有两种方式可以设置外键:基于字符串的声明基于类的声明。基于字符串的声明更适合简单的数据类型声明。

基于字符串的声明

打开您的fk_datatypes_path文件,并在数组中添加外键声明。数组键是外键列,其值是数据类型。引用表已经智能地猜测出来了,方法是通过移除_id并将外键名称复数化,例如user_id -> users

<?php

return [
    'user_id'       => 'unsignedInteger',
    'group_id'      => 'unsignedInteger',
    'preference_id' => 'unsignedBigInteger',
];

自1.2版本起,您现在也可以定义引用表。这对于具有自定义表名的外键非常有用。

<?php

return [
    'user_id'       => 'unsignedInteger, custom_users',
    'group_id'      => 'unsignedInteger, custom_groups',
];
基于类的声明

在您的fk_namespace目录路径中创建外键声明类的文件。

命名约定

如果外键是例如user_id,那么类名应该是UserId

示例

<?php

namespace Your\Fk\Namespace;

use FkAdder\BaseFk;

class UserId extends BaseFk
{
    protected $referenceTable = 'users';

    public function createFkColumn($column)
    {
        return $this->table->unsignedInteger($column);
    }
}

示例用法,前后对比

之前

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('group_id')->nullable()->comment('Group of the user');
            $table->unsignedBigInteger('preference_id')->nullable()->comment('Preference of the user');

            $table->foreign('group_id')->references('id')->on('groups');
            $table->foreign('preference_id')->references('id')->on('preferences')
                ->onDelete('cascade')>onUpdate('cascade');
        });
    }
}

之后

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table) {
            $table->increments('id');

            Fk::make($table)->add('group_id')->nullable()->comment('Group of the user');

            Fk::make($table)
                ->onDelete('cascade')
                ->onUpdate('cascade')
                ->add('preference_id')
                ->nullable()
                ->comment('Preference of the user');
        });

        Fk::migrate();
    }
}

更多功能、优势和解释

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateUsersTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('users', function(Blueprint $table) {
            $table->increments('id');

            // Foreign key declaration is one-liner, simpler and more compact.
            // You dont have to type what datatype it is. You will just declare it once.
            Fk::make($table)->add('group_id')->nullable()->comment('Group of the user');
            Fk::make($table)->onDelete('cascade')->add('preference_id')
                ->nullable()->comment('Preference of the user');

            // After you call the method `add()`, it will return an instance of the usual \Illuminate\Support\Fluent,
            // so that you can chain more column declaration like `nullable()` and `comment()`

            // If ever you need a different column name from the foreign key, just pass a second parameter
            // to `add()` method e.g.
            Fk::make($table)->add('group_id', 'new_group_id')->nullable()->comment('New group of the user');

            // The default `onDelete` settings is `restrict` and `onUpdate` is `cascade`.
            Fk::make($table)->onDelete('restrict')->onUpdate('cascade')->add('group_id', 'new_group_id');

            // You can also pass the key name for the foreign key.
            Fk::make($table)->keyName('users_new_group_id_foreign_key')->add('group_id', 'new_group_id');

            // Take note that those foreign key modifiers should be called prior or before the `add()` method.
        });

        // Finally, you may now migrate and persist foreign keys in mysql database.
        // You can call this once at the very end of migration,
        // so all your foreign key declarations accross different migration files will be persisted.
        Fk::migrate();
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Fk::rollback(); // delete foreign keys persisted by Fk::migrate(), (coming soon...)
        Schema::dropIfExists('users');
    }
}

许可

在MIT许可下发布。