Readouble

Laravel 5.2 データベース:マイグレーション

イントロダクションIntroduction

マイグレーションとはデータベースのバージョンコントロールのようなもので、チームでアプリケーションデータベースのスキーマを簡単に更新し共有できるようにしてくれます。通常、マイグレーションはアプリケーションのデータベーススキーマを簡単に構築できるようにする、Laravelのスキーマビルダと一緒に使用します。Migrations are like version control for your database, allowing a team to easily modify and share the application's database schema. Migrations are typically paired with Laravel's schema builder to easily build your application's database schema.

LaravelのSchemaファサードはテーブルの作成や操作をどのデータベースエンジンを使うかに関わらずサポートします。Laravelがサポートしているデータベースシステム全部で同じ記述法と書きやすいAPIを共用できます。The Laravel Schema facade[/docs/{{version}}/facades] provides database agnostic support for creating and manipulating tables. It shares the same expressive, fluent API across all of Laravel's supported database systems.

マイグレーション生成Generating Migrations

make:migration Artisanコマンドを使いマイグレーションを生成できます。To create a migration, use the make:migration Artisan command[/docs/{{version}}/artisan]:

php artisan make:migration create_users_table

マイグレーションはdatabase/migrationsフォルダーに設置されます。マイグレーションの実行順をフレームワークに知らせるため、名前にタイムスタンプが含まれています。The new migration will be placed in your database/migrations directory. Each migration file name contains a timestamp which allows Laravel to determine the order of the migrations.

--table--createオプションも、テーブル名とマイグレーションで新しいテーブルを生成するかを指定するために使用できます。これらのオプションは生成するマイグレーションスタブの中へ指定したテーブルをただ予め埋め込みます。The --table and --create options may also be used to indicate the name of the table and whether the migration will be creating a new table. These options simply pre-fill the generated migration stub file with the specified table:

php artisan make:migration add_votes_to_users_table --table=users

php artisan make:migration create_users_table --create=users

マイグレーションの生成出力先のパスを指定したい場合は、make:migrateコマンドの実行時に--pathオプションを付けてください。パスはアプリケーションのベースパスからの相対位置です。If you would like to specify a custom output path for the generated migration, you may use the --path option when executing the make:migration command. The provided path should be relative to your application's base path.

マイグレーション構造Migration Structure

マイグレーションはupdownの2メソッドを含んでいます。upメソッドは新しいテーブル、カラム、インデックスをデータベースに追加するために使用し、一方のdownメソッドはupメソッドが行った操作を元に戻します。A migration class contains two methods: up and down. The up method is used to add new tables, columns, or indexes to your database, while the down method should simply reverse the operations performed by the up method.

両方のメソッドで記述的にテーブルを作成したり、変更したりできるLaravelスキーマビルダを使えます。Schemaビルダで使用できる全メソッドは、このドキュメント後半で確認してください。例としてflightsテーブルを作成するマイグレーションを見てください。Within both of these methods you may use the Laravel schema builder to expressively create and modify tables. To learn about all of the methods available on the Schema builder, check out its documentation[#creating-tables]. For example, let's look at a sample migration that creates a flights table:

<?php

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

class CreateFlightsTable extends Migration
{
    /**
     * マイグレーション実行
     *
     * @return void
     */
    public function up()
    {
        Schema::create('flights', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('airline');
            $table->timestamps();
        });
    }

    /**
     * マイグレーションを元に戻す
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('flights');
    }
}

マイグレーション実行Running Migrations

アプリケーションで用意したマイグレーションを全部実行するには、migrate Artisanコマンドを使用します。Homestead仮想マシーンを使用している場合は、VMの中でこのコマンドを実行してください。To run all outstanding migrations for your application, use the migrate Artisan command. If you are using the Homestead virtual machine[/docs/{{version}}/homestead], you should run this command from within your VM:

php artisan migrate

マイグレーション中に"class not found"エラーが出る場合は、composer dump-autoloadを実行し、その後に再実行してください。If you receive a "class not found" error when running migrations, try running the composer dump-autoload command and re-issuing the migrate command.

実働環境でのマイグレーション強制Forcing Migrations To Run In Production

いくつかのマイグレーション操作は破壊的です。つまりデーターを失う可能性があります。実働環境(production)のデータベースでこうしたコマンドが実行されることから保護するために、コマンド実行前に確認のプロンプトが表示されます。コマンド実行時のプロンプトを出さないためには、--forceフラグを指定してください。Some migration operations are destructive, meaning they may cause you to lose data. In order to protect you from running these commands against your production database, you will be prompted for confirmation before these commands are executed. To force the commands to run without a prompt, use the --force flag:

php artisan migrate --force

ロールバックRolling Back Migrations

最後のマイグレーション「操作」をロールバックしたい場合は、rollbackコマンドを使います。このロールバックで注意してもらいたのは、「一度」に実行した最後のマイグレーションを元に戻すため、複数のマイグレーションファイル分の操作が巻き戻されることがある点です。To rollback the latest migration "operation", you may use the rollback command. Note that this rolls back the last "batch" of migrations that ran, which may include multiple migration files:

php artisan migrate:rollback

migrate:resetコマンドはアプリケーション全部のマイグレーションをロールバックします。The migrate:reset command will roll back all of your application's migrations:

php artisan migrate:reset

rollbackとmigrateの1コマンド実行Rollback / Migrate In Single Command

migrate:refreshコマンドは全部のデータベースマイグレーションを最初にロールバックし、それからmigrateコマンドを実行します。このコマンドはデータベース全体を作り直すために便利です。The migrate:refresh command will first roll back all of your database migrations, and then run the migrate command. This command effectively re-creates your entire database:

php artisan migrate:refresh

php artisan migrate:refresh --seed

マイグレーション記述Writing Migrations

テーブル作成Creating Tables

新しいデータベーステーブルを作成するには、Schemaファサードのcreateメソッドを使用します。createメソッドは引数を2つ取ります。最初はテーブルの名前で、2つ目は新しいテーブルを定義するために使用するBlueprintオブジェクトを受け取る「クロージャ」です。To create a new database table, use the create method on the Schema facade. The create method accepts two arguments. The first is the name of the table, while the second is a Closure which receives a Blueprint object used to define the new table:

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

もちろんテーブル作成時には、テーブルのカラムを定義するためにスキーマビルダのカラムメソッドをどれでも利用できます。Of course, when creating the table, you may use any of the schema builder's column methods[#creating-columns] to define the table's columns.

テーブル/カラムの存在チェックChecking For Table / Column Existence

hasTablehasColumnメソッドを使えば、テーブルやカラムの存在を簡単にチェックできます。You may easily check for the existence of a table or column using the hasTable and hasColumn methods:

if (Schema::hasTable('users')) {
    //
}

if (Schema::hasColumn('users', 'email')) {
    //
}

接続とストレージエンジンConnection & Storage Engine

デフォルト接続以外のデータベース接続でスキーマ操作を行いたい場合は、connectionメソッドを使ってください。If you want to perform a schema operation on a database connection that is not your default connection, use the connection method:

Schema::connection('foo')->create('users', function ($table) {
    $table->increments('id');
});

テーブルのストレージエンジンを指定する場合は、スキーマビルダのengineプロパティを設定します。To set the storage engine for a table, set the engine property on the schema builder:

Schema::create('users', function ($table) {
    $table->engine = 'InnoDB';

    $table->increments('id');
});

テーブルリネーム/削除Renaming / Dropping Tables

既存のデータベーステーブルの名前を変えたい場合は、renameメソッドを使います。To rename an existing database table, use the rename method:

Schema::rename($from, $to);

存在するテーブルを削除する場合は、dropdropIfExistsメソッドを使います。To drop an existing table, you may use the drop or dropIfExists methods:

Schema::drop('users');

Schema::dropIfExists('users');

外部キーを持つテーブルのリネームRenaming Tables With Foreign Keys

テーブルのリネームを行う前に、Laravelの規約に基づいた名前の代わりに、マイグレーションファイル中で独自の名前付けた外部キー制約が存在していないか確認してください。そうしないと、外部キー制約名は古いテーブル名を参照してしまいます。Before renaming a table, you should verify that any foreign key constraints on the table have an explicit name in your migration files instead of letting Laravel assign a convention based name. Otherwise, the foreign key constraint name will refer to the old table name.

カラム作成Creating Columns

存在するテーブルを更新するには、Schemaファサードのtableメソッドを使います。createメソッドと同様にtableメソッドは2つの引数を取ります。テーブルの名前と、テーブルにカラムを追加するために使用するBlueprintインスタンスを受け取る「クロージャ」です。To update an existing table, we will use the table method on the Schema facade. Like the create method, the table method accepts two arguments: the name of the table and a Closure that receives a Blueprint instance we can use to add columns to the table:

Schema::table('users', function ($table) {
    $table->string('email');
});

使用できるカラムタイプAvailable Column Types

当然ながらスキーマビルダは、テーブルを構築する時に使用する様々なカラムタイプを持っています。Of course, the schema builder contains a variety of column types that you may use when building your tables:

コマンドCommand 説明Description
$table->bigIncrements('id');$table->bigIncrements('id'); 「符号なしBIGINT」を使用した自動増分ID(主キー)Incrementing ID (primary key) using a "UNSIGNED BIG INTEGER" equivalent.
$table->bigInteger('votes');$table->bigInteger('votes'); BIGINTカラムBIGINT equivalent for the database.
$table->binary('data');$table->binary('data'); BLOBカラムBLOB equivalent for the database.
$table->boolean('confirmed');$table->boolean('confirmed'); BOOLEANカラムBOOLEAN equivalent for the database.
$table->char('name', 4);$table->char('name', 4); 長さを指定するCHARカラムCHAR equivalent with a length.
$table->date('created_at');$table->date('created_at'); DATEカラムDATE equivalent for the database.
$table->dateTime('created_at');$table->dateTime('created_at'); DATETIMEカラムDATETIME equivalent for the database.
$table->dateTimeTz('created_at');$table->dateTimeTz('created_at'); タイムゾーン付きDATETIMEカラムDATETIME (with timezone) equivalent for the database.
$table->decimal('amount', 5, 2);$table->decimal('amount', 5, 2); 有効/小数点以下桁数指定のDECIMALカラムDECIMAL equivalent with a precision and scale.
$table->double('column', 15, 8);$table->double('column', 15, 8); 15桁、小数点以下8桁のDOUBLEカラムDOUBLE equivalent with precision, 15 digits in total and 8 after the decimal point.
$table->enum('choices', ['foo', 'bar']);$table->enum('choices', ['foo', 'bar']); ENUMカラムENUM equivalent for the database.
$table->float('amount');$table->float('amount'); FLOATカラムFLOAT equivalent for the database.
$table->increments('id');$table->increments('id'); 「符号なしINT」を使用した自動増分ID(主キー)Incrementing ID (primary key) using a "UNSIGNED INTEGER" equivalent.
$table->integer('votes');$table->integer('votes'); INTEGERカラムINTEGER equivalent for the database.
$table->ipAddress('visitor');$table->ipAddress('visitor'); IPアドレスカラムIP address equivalent for the database.
$table->json('options');$table->json('options'); JSONフィールドJSON equivalent for the database.
$table->jsonb('options');$table->jsonb('options'); JSONBフィールドJSONB equivalent for the database.
$table->longText('description');$table->longText('description'); LONGTEXTカラムLONGTEXT equivalent for the database.
$table->macAddress('device');$table->macAddress('device'); MACアドレスカラムMAC address equivalent for the database.
$table->mediumInteger('numbers');$table->mediumInteger('numbers'); MEDIUMINTカラムMEDIUMINT equivalent for the database.
$table->mediumText('description');$table->mediumText('description'); MEDIUMTEXTカラムMEDIUMTEXT equivalent for the database.
$table->morphs('taggable');$table->morphs('taggable'); INTERGERのtaggable_idと文字列のtaggable_typeを追加Adds INTEGER taggable_id and STRING taggable_type.
$table->nullableTimestamps();$table->nullableTimestamps(); NULL値を許す以外、timestamps()と同じSame as timestamps(), except allows NULLs.
$table->rememberToken();$table->rememberToken(); VARCHAR(100) NULLのremember_tokenを追加Adds remember_token as VARCHAR(100) NULL.
$table->smallInteger('votes');$table->smallInteger('votes'); SMALLINTカラムSMALLINT equivalent for the database.
$table->softDeletes();$table->softDeletes(); ソフトデリートのためのdeleted_atカラム追加Adds deleted_at column for soft deletes.
$table->string('email');$table->string('email'); VARCHARカラムVARCHAR equivalent column.
$table->string('name', 100);$table->string('name', 100); 長さ指定のVARCHARカラムVARCHAR equivalent with a length.
$table->text('description');$table->text('description'); TEXTカラムTEXT equivalent for the database.
$table->time('sunrise');$table->time('sunrise'); TIMEカラムTIME equivalent for the database.
$table->timeTz('sunrise');$table->timeTz('sunrise'); タイムゾーン付きTIMEカラムTIME (with timezone) equivalent for the database.
$table->tinyInteger('numbers');$table->tinyInteger('numbers'); TINYINTカラムTINYINT equivalent for the database.
$table->timestamp('added_on');$table->timestamp('added_on'); TIMESTAMPカラムTIMESTAMP equivalent for the database.
$table->timestampTz('added_on');$table->timestampTz('added_on'); タイムゾーン付きTIMESTAMPカラムTIMESTAMP equivalent for the database.
$table->timestamps();$table->timestamps(); created_atupdate_atカラムの追加Adds created_at and updated_at columns.
$table->uuid('id');$table->uuid('id'); データベース向けのUUID類似値UUID equivalent for the database.

カラム修飾子Column Modifiers

上記のカラムタイプに付け加え、カラムを追加するときに使用できる様々な修飾子もあります。たとえばカラムを「NULL値設定可能(nullable)」にしたい場合は、nullableメソッドを使います。In addition to the column types listed above, there are several other column "modifiers" which you may use while adding the column. For example, to make the column "nullable", you may use the nullable method:

Schema::table('users', function ($table) {
    $table->string('email')->nullable();
});

下表が使用可能なカラム修飾子の一覧です。インデックス修飾子は含まれていません。Below is a list of all the available column modifiers. This list does not include the index modifiers[#creating-indexes]:

修飾子Modifier 説明Description
->first()->first() カラムをテーブルの最初(first)に設置する(MySQLのみ)Place the column "first" in the table (MySQL Only)
->after('column')->after('column') 指定カラムの次にカラムを設置する(MySQLのみ)Place the column "after" another column (MySQL Only)
->nullable()->nullable() カラムにNULL値を許すAllow NULL values to be inserted into the column
->default($value)->default($value) カラムのデフォルト(default)値設定Specify a "default" value for the column
->unsigned()->unsigned() 整数(integer)を符号(unsigned)Set integer columns to UNSIGNED
->comment('my comment')->comment('my comment') カラムにコメント追加Add a comment to a column

カラム変更Modifying Columns

動作要件Prerequisites

カラムを変更する前に、composer.jsonファイルでdoctrine/dbalを確実に追加してください。Doctrine DBALライブラリーは現在のカラムの状態を決め、指定されたカラムに対する修正を行うSQLを生成します。Before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column.

カラム属性の変更Updating Column Attributes

changeメソッドは存在するカラムを新しいタイプへ変更するか、カラムの属性を変えます。たとえば文字列の長さを増やしたい場合です。changeの実例を見てもらうため、nameカラムのサイズを25から50へ増やしてみます。The change method allows you to modify an existing column to a new type, or modify the column's attributes. For example, you may wish to increase the size of a string column. To see the change method in action, let's increase the size of the name column from 25 to 50:

Schema::table('users', function ($table) {
    $table->string('name', 50)->change();
});

さらにカラムをNULL値設定可能にしてみましょう。We could also modify a column to be nullable:

Schema::table('users', function ($table) {
    $table->string('name', 50)->nullable()->change();
});

注意: カラムタイプがenumjsonjsonbのテーブル中のカラム属性変更は、現在サポートしていません。Note: Modifying any column in a table that also has a column of type enum is not currently supported.

カラム名変更Renaming Columns

カラム名を変更するには、renameColumnメソッドをスキーマビルダで使用してください。カラム名を変更する前に、composer.jsonファイルでdoctrine/dbalを依存パッケージとして追加してください。To rename a column, you may use the renameColumn method on the Schema builder. Before renaming a column, be sure to add the doctrine/dbal dependency to your composer.json file:

Schema::table('users', function ($table) {
    $table->renameColumn('from', 'to');
});

注意: カラムタイプがenumjsonjsonbのテーブル中のカラム名変更は、現在サポートしていません。Note: Renaming any column in a table that also has a column of type enum is not currently supported.

カラム削除Dropping Columns

カラムをドロップするには、スキーマビルダのdropColumnメソッドを使用します。To drop a column, use the dropColumn method on the Schema builder:

Schema::table('users', function ($table) {
    $table->dropColumn('votes');
});

dropColumnメソッドにカラム名の配列を渡せば、テーブルから複数のカラムをドロップできます。You may drop multiple columns from a table by passing an array of column names to the dropColumn method:

Schema::table('users', function ($table) {
    $table->dropColumn(['votes', 'avatar', 'location']);
});

注意 SQLiteデータベースからカラムをドロップする場合は、事前にcomposer.jsonファイルへdoctrine/dbal依存パッケージを追加してください。その後にライブラリーをインストールするため、composer updateを実行してください。Note: Before dropping columns from a SQLite database, you will need to add the doctrine/dbal dependency to your composer.json file and run the composer update command in your terminal to install the library.

注意: SQLite使用時に、一つのマイグレーションによる複数カラム削除/変更はサポートされていません。Note: Dropping or modifying multiple columns within a single migration while using a SQLite database is not supported.

インデックス作成Creating Indexes

スキーマビルダは様々なインデックスタイプをサポートしています。まず指定したカラムの値を一意にする例を見てください。インデックスを作成するには、カラム定義にuniqueメソッドをチェーンで付け加えるだけです。The schema builder supports several types of indexes. First, let's look at an example that specifies a column's values should be unique. To create the index, we can simply chain the unique method onto the column definition:

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

もしくはカラム定義の後でインデックスを作成することも可能です。例を見てください。Alternatively, you may create the index after defining the column. For example:

$table->unique('email');

インデックスメソッドにカラムの配列を渡し、複合インデックスを作成することもできます。You may even pass an array of columns to an index method to create a compound index:

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

Laravelは自動的に、わかりやすいインデックス名を付けます。しかしメソッドの第2引数で、名前を指定することもできます。Laravel will automatically generate a reasonable index name, but you may pass a second argument to the method to specify the name yourself:

$table->index('email', 'my_index_name');

使用可能なインデックスタイプAvailable Index Types

コマンドCommand 説明Description
$table->primary('id');$table->primary('id'); 主キー追加Add a primary key.
$table->primary(['first', 'last']);$table->primary(['first', 'last']); 複合キー追加Add composite keys.
$table->unique('email');$table->unique('email'); uniqueキー追加Add a unique index.
$table->unique('state', 'my_index_name');$table->unique('state', 'my_index_name'); インデックス名のカスタマイズAdd a custom index name.
$table->index('state');$table->index('state'); 基本的なインデックス追加Add a basic index.

インデックス削除Dropping Indexes

インデックスを削除する場合はインデックスの名前を指定します。Laravelはデフォルトで意味が通る名前をインデックスに付けます。シンプルにテーブル名、インデックスしたカラム名、インデックスタイプをつなげたものです。いくつか例をご覧ください。To drop an index, you must specify the index's name. By default, Laravel automatically assigns a reasonable name to the indexes. Simply concatenate the table name, the name of the indexed column, and the index type. Here are some examples:

コマンドCommand 説明Description
$table->dropPrimary('users_id_primary');$table->dropPrimary('users_id_primary'); "users"テーブルから主キーを削除Drop a primary key from the "users" table.
$table->dropUnique('users_email_unique');$table->dropUnique('users_email_unique'); "users"テーブルからユニークキーを削除Drop a unique index from the "users" table.
$table->dropIndex('geo_state_index');$table->dropIndex('geo_state_index'); "geo"テーブルから基本インデックスを削除Drop a basic index from the "geo" table.

カラムの配列をインデックス削除メソッドに渡すと、テーブル、カラム、キータイプに基づき、命名規則に従ったインデックス名が生成されます。If you pass an array of columns into a method that drops indexes, the conventional index name will be generated based on the table name, columns and key type.

Schema::table('geo', function ($table) {
    $table->dropIndex(['state']); // Drops index 'geo_state_index'
});

外部キー制約Foreign Key Constraints

Laravelはデータベースレベルの整合性を強制するために、テーブルに対する外部キー束縛の追加も提供しています。たとえばusersテーブルのidカラムを参照する、postsテーブルのuser_idカラムを定義してみましょう。Laravel also provides support for creating foreign key constraints, which are used to force referential integrity at the database level. For example, let's define a user_id column on the posts table that references the id column on a users table:

Schema::table('posts', function ($table) {
    $table->integer('user_id')->unsigned();

    $table->foreign('user_id')->references('id')->on('users');
});

さらに束縛に対して「デリート時(on delete)」と「更新時(on update)」に対する処理をオプションとして指定できます。You may also specify the desired action for the "on delete" and "on update" properties of the constraint:

$table->foreign('user_id')
      ->references('id')->on('users')
      ->onDelete('cascade');

外部キーを削除するには、dropForeignメソッドを使用します。他のインデックスで使用されるものと似た命名規則が、外部キーにも使用されています。つまりテーブル名とカラム名をつなげ、"_foreign"を最後につけた名前になります。To drop a foreign key, you may use the dropForeign method. Foreign key constraints use the same naming convention as indexes. So, we will concatenate the table name and the columns in the constraint then suffix the name with "_foreign":

$table->dropForeign('posts_user_id_foreign');

もしくは配列値を渡せば、削除時に自動的に命名規則に従った名前が使用されます。Or you may pass an array value which will automatically use the conventional constraint name when dropping:

$table->dropForeign(['user_id']);

以下のメソッドにより、マイグレーション中の外部キー制約の有効/無効を変更できます。You may enable or disable foreign key constraints within your migrations by using the following methods:

Schema::enableForeignKeyConstraints();

Schema::disableForeignKeyConstraints();

章選択

設定

明暗テーマ
light_mode
dark_mode
brightness_auto システム設定に合わせる
テーマ選択
photo_size_select_actual デフォルト
photo_size_select_actual モノクローム(白黒)
photo_size_select_actual Solarized風
photo_size_select_actual GitHub風(青ベース)
photo_size_select_actual Viva(黄緑ベース)
photo_size_select_actual Happy(紫ベース)
photo_size_select_actual Mint(緑ベース)
コードハイライトテーマ選択

明暗テーマごとに、コードハイライトのテーマを指定できます。

テーマ配色確認
スクリーン表示幅
640px
80%
90%
100%

768px以上の幅があるときのドキュメント部分表示幅です。

インデント
無し
1rem
2rem
3rem
原文確認
原文を全行表示
原文を一行ずつ表示
使用しない

※ 段落末のEボタンへカーソルオンで原文をPopupします。

Diff表示形式
色分けのみで区別
行頭の±で区別
削除線と追記で区別

※ [tl!…]形式の挿入削除行の表示形式です。

Pagination和文
ペジネーション
ペギネーション
ページネーション
ページ付け
Scaffold和文
スカフォールド
スキャフォールド
型枠生成
本文フォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

コードフォント

総称名以外はCSSと同様に、"〜"でエスケープしてください。

保存内容リセット

localStrageに保存してある設定項目をすべて削除し、デフォルト状態へ戻します。

ヘッダー項目移動

キーボード操作