Readouble

Laravel 5.0 スキーマビルダー

イントロダクションIntroduction

LaravelのSchemaクラスは、データベースエンジンに拠らないテーブル操作方法を提供しています。これはLaravelがサポートしている全てのデータベースで上手く動作し、共通のAPIを持っています。The Laravel Schema class provides a database agnostic way of manipulating tables. It works well with all of the databases supported by Laravel, and has a unified API across all of these systems.

テーブル作成/削除Creating & Dropping Tables

テーブルを作成するには、Schema::createメソッドを使用します。To create a new database table, the Schema::create method is used:

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

createメソッドの最初の引数はテーブル名で、2つ目は無名関数です。新しいテーブルを定義するためのBlueprintオブジェクトを取ります。The first argument passed to the create method is the name of the table, and the second is a Closure which will receive a Blueprint object which may be used to define the new table.

存在しているテーブルの名前を変更するにはrenameメソッドを使用してください。To rename an existing database table, the rename method may be used:

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

スキーマ操作のコネクションを指定するには、Schema::connectionメソッドを最初に使用します。To specify which connection the schema operation should take place on, use the Schema::connection method:

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

テーブルをドロップするためには、Schema::dropメソッドを使用します。To drop a table, you may use the Schema::drop method:

Schema::drop('users');

Schema::dropIfExists('users');

カラム追加Adding Columns

既に存在するテーブルを更新するには、Schema::tableメソッドを使用します。To update an existing table, we will use the Schema::table method:

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

テーブルビルダーは構築に使用する様々なカラムのタイプで構成されています。The table builder contains a variety of column types that you may use when building your tables:

コマンドCommand 説明Description
$table->bigIncrements('id');$table->bigIncrements('id'); BIGINTを使用した自動増分IDIncrementing ID using a "big integer" equivalent
$table->bigInteger('votes');$table->bigInteger('votes'); BIGINTカラムBIGINT equivalent to the table
$table->binary('data');$table->binary('data'); BLOBカラムBLOB equivalent to the table
$table->boolean('confirmed');$table->boolean('confirmed'); BOOLEANカラムBOOLEAN equivalent to the table
$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 to the table
$table->dateTime('created_at');$table->dateTime('created_at'); DATETIMEカラムDATETIME equivalent to the table
$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 to the table
$table->float('amount');$table->float('amount'); FLOATカラムFLOAT equivalent to the table
$table->increments('id');$table->increments('id'); 自動増分ID(主キー)Incrementing ID to the table (primary key)
$table->integer('votes');$table->integer('votes'); INTEGERカラムINTEGER equivalent to the table
$table->json('options');$table->json('options'); JSONフィールドJSON equivalent to the table
$table->jsonb('options');$table->jsonb('options'); JSONBフィールドJSONB equivalent to the table
$table->longText('description');$table->longText('description'); LONGTEXTカラムLONGTEXT equivalent to the table
$table->mediumInteger('numbers');$table->mediumInteger('numbers'); MEDIUMINTカラムMEDIUMINT equivalent to the table
$table->mediumText('description');$table->mediumText('description'); MEDIUMTEXTカラムMEDIUMTEXT equivalent to the table
$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->smallInteger('votes');$table->smallInteger('votes'); SMALLINTカラムSMALLINT equivalent to the table
$table->tinyInteger('numbers');$table->tinyInteger('numbers'); TINYINTカラムTINYINT equivalent to the table
$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 to the table
$table->time('sunrise');$table->time('sunrise'); TIMEカラムTIME equivalent to the table
$table->timestamp('added_on');$table->timestamp('added_on'); TIMESTAMPカラムTIMESTAMP equivalent to the table
$table->timestamps();$table->timestamps(); created_atupdate_atカラムの追加Adds created_at and updated_at columns
$table->rememberToken();$table->rememberToken(); VARCHAR(100) NULLのremember_tokenを追加Adds remember_token as VARCHAR(100) NULL
->nullable()->nullable() カラムにNULL値を許すDesignate that the column allows NULL values
->default($value)->default($value) カラムのデフォルト値設定Declare a default value for a column
->unsigned()->unsigned() INTEGERを符号なしにするSet INTEGER to UNSIGNED

MySQLでafterメソッド使用Using After On MySQL

MySQLデータベースをお使いでしたら、afterメソッドでカラムの順番を指定することができます。If you are using the MySQL database, you may use the after method to specify the order of columns:

$table->string('name')->after('email');

カラム変更Changing Columns

注意 カラムを変更する前に、composer.jsonファイルへdoctrine/dbal依存パッケージを追加し、インストールしてください。Note: Before changing a column, be sure to add the doctrine/dbal dependency to your composer.json file.

まれに既存のカラムを変更する必要がある場合もあります。例えば、文字列のサイズを大きくしたい場合などです。changeメソッドを使えば、簡単にできます! 例えば、nameのサイズを50桁に広げる場合は、次のようにします。Sometimes you may need to modify an existing column. For example, you may wish to increase the size of a string column. The change method makes it easy! For example, let's increase the size of the name column from 25 to 50:

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

また、カラムにNULLを許す(NULLABLE)場合は、以下の通りです。We could also modify a column to be nullable:

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

カラム名変更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');
});

Note: enumカラムを含んでいるテーブルのカラム名変更は、現在サポートしていません。Note: Renaming columns in a table with enum column is currently not supported.

カラム削除Dropping Columns

カラムをドロップするには、スキーマビルダーのdropColumnメソッドを使用します。カラムをドロップする前に、composer.jsonファイルへdoctrine/dbal依存パッケージを追加してください。To drop a column, you may use the dropColumn method on the Schema builder. Before dropping a column, be sure to add the doctrine/dbal dependency to your composer.json file.

データベーステーブルからカラムをドロップDropping A Column From A Database Table

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

データベーステーブルから複数のカラムをドロップDropping Multiple Columns From A Database Table

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

存在チェックChecking Existence

テーブルの存在確認Checking For Existence Of Table

hasTablehasColumnを使用し簡単にテーブル、カラムが存在するかチェックできます。You may easily check for the existence of a table or column using the hasTable and hasColumn methods:

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

カラムの存在確認Checking For Existence Of Columns

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

インデックス追加Adding Indexes

スキーマビルダーは様々なインデックスタイプをサポートしています。追加方法は2つあります。カラムの定義と同時に記述する方法と、後から追加する方法です。The schema builder supports several types of indexes. There are two ways to add them. First, you may fluently define them on a column definition, or you may add them separately:

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

もしくは、別の行でインデックスを追加することを選べます。指定可能なインデックスタイプの一覧です。Or, you may choose to add the indexes on separate lines. Below is a list of all available index types:

コマンドCommand 説明Description
$table->primary('id');$table->primary('id'); 主キーを追加Adding a primary key
$table->primary(['first', 'last']);$table->primary(['first', 'last']); 複合キーを追加Adding composite keys
$table->unique('email');$table->unique('email'); ユニークキーを追加Adding a unique index
$table->index('state');$table->index('state'); 基本的なインデックスを追加Adding a basic index

外部キーForeign Keys

Laravelはテーブルに対する、外部キー束縛の追加も提供しています。Laravel also provides support for adding foreign key constraints to your tables:

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

この例では、user_idカラムがusersテーブルのidカラムを参照していることを宣言しています。外部キーカラムを最初に作成するのを忘れないでください。In this example, we are stating that the user_id column references the id column on the users table. Make sure to create the foreign key column first!

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

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

外部キーを削除するには、dropForeignメソッドを使用します。他のインデックスで使用されるものと似た命名規則が、外部キーにも使用されています。To drop a foreign key, you may use the dropForeign method. A similar naming convention is used for foreign keys as is used for other indexes:

$table->dropForeign('posts_user_id_foreign');

Note: 自動増分する整数として参照される外部キーを作成する場合、外部キーの項目作成時はいつでもunsignedを付けるのをお忘れなく。Note: When creating a foreign key that references an incrementing integer, remember to always make the foreign key column unsigned.

インデックス削除Dropping Indexes

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

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

タイムスタンプとソフトデリートフィールド削除Dropping Timestamps & SoftDeletes

timestampsnullableTimestampssoftDeletesのカラムタイプを削除するためには、以下のメソッドが使用できます。To drop the timestamps, nullableTimestamps or softDeletes column types, you may use the following methods:

コマンドCommand 説明Description
$table->dropTimestamps();$table->dropTimestamps(); created_atupdate_atカラムの削除Dropping the created_at and updated_at columns from the table
$table->dropSoftDeletes();$table->dropSoftDeletes(); deleted_atカラムの削除Dropping deleted_at column from the table

ストレージエンジンStorage Engines

テーブルにストレージエンジンを設定するには、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->string('email');
});

章選択

Artisan CLI

設定

明暗テーマ
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!…]形式の挿入削除行の表示形式です。

テストコード表示
両コード表示
Pestのみ表示
PHPUnitのみ表示
和文変換

対象文字列と置換文字列を半角スペースで区切ってください。(最大5組各10文字まで)

本文フォント

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

コードフォント

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

保存内容リセット

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

ヘッダー項目移動

キーボード操作