37
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

Laravel7 新たに追加された3つのマイグレーションエイリアス

Last updated at Posted at 2020-03-23

Laravel7 で追加されたマイグレーションエイリアス

使用できるカラムタイプのエイリアス

  • id
  • foreignId

外部キー制約のエイリアス

  • constrained

上記の3つのエイリアスが追加されてます。

環境

$ php artisan -V
Laravel Framework 7.2.2

使い方

Schema::table('posts', function (Blueprint $table) {
    $table->id();
    $table->foreignId('user_id')->constrained();
});

上の定義は、下記のように定義したのと同じ内容になります。

Schema::table('posts', function (Blueprint $table) {
    $table->bigIncrements('id');
    $table->unsignedBigInteger('user_id');
    $table->foreign('user_id')->references('id')->on('users');
});

補足

id

src/Illuminate/Database/Schema/Blueprint.php
    /**
     * Create a new auto-incrementing big integer (8-byte) column on the table.
     *
     * @param  string  $column
     * @return \Illuminate\Database\Schema\ColumnDefinition
     */
    public function id($column = 'id')
    {
        return $this->bigIncrements($column);
    }

シンプルなエイリアスですね。
個人的には bigIncrements って指定されてた方が分かりやすいと思うんですけど...

foreignId

src/Illuminate/Database/Schema/Blueprint.php
    /**
     * Create a new unsigned big integer (8-byte) column on the table.
     *
     * @param  string  $column
     * @return \Illuminate\Database\Schema\ForeignIdColumnDefinition
     */
    public function foreignId($column)
    {
        $this->columns[] = $column = new ForeignIdColumnDefinition($this, [
            'type' => 'bigInteger',
            'name' => $column,
            'autoIncrement' => false,
            'unsigned' => true,
        ]);

        return $column;
    }

ForeignIdColumnDefinition のインスタンスが返ってきますね。

constrained

src/Illuminate/Database/Schema/ForeignIdColumnDefinition.php
    /**
     * Create a foreign key constraint on this column referencing the "id" column of the conventionally related table.
     *
     * @param  string|null  $table
     * @return \Illuminate\Support\Fluent|\Illuminate\Database\Schema\ForeignKeyDefinition
     */
    public function constrained($table = null)
    {
        return $this->references('id')->on($table ?: Str::plural(Str::before($this->name, '_id')));
    }

foreignId に返ってきた ForeignIdColumnDefinition にメソッドチェーンでつなげて呼び出します。
$table->foreign('user_id')->references('id')->on('users'); このようにテーブル名を指定しますが、 ->foreign('user_id') から users と複数形のテーブルを自動的に設定してくれます。

37
26
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
37
26

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?