🏰

Laravel migrations関係のメモ

2024/06/14に公開

Schemaを作成する際の注意点

integerでautoIncrement,unsignedの設定

integerの引数は以下のような設定になっており、第2引数でautoIncrement、第3引数でunsignedを設定することが可能である。
直感的ではないが、autoIncrement()やunsigned()を使わない書き方もできることは頭に入れておいても良いかもしれない。

integer($column, $autoIncrementbool, $unsignedbool)
    /**
     * Create a new integer (4-byte) column on the table.
     *
     * @param  string  $column
     * @param  bool  $autoIncrement
     * @param  bool  $unsigned
     * @return \Illuminate\Database\Schema\ColumnDefinition
     */

参考記事:
https://qiita.com/haruraruru/items/8ed08a5dfd719ebb9a2e

マイグレーションの修飾子

修飾子 説明
->after('column') カラムを別のカラムの「後に」配置(MySQL)
->autoIncrement() INTEGERカラムを自動増分(主キー)として設定
->charset('utf8mb4') カラムの文字セットを指定(MySQL)
->collation('utf8mb4_unicode_ci') カラムの照合順序を指定(MySQL/PostgreSQL/SQL Server)
->comment('my comment') カラムにコメントを追加(MySQL/PostgreSQL)
->default($value) カラムの「デフォルト」値を指定
->first() テーブルの「最初の」カラムを配置(MySQL)
->from($integer) 自動増分フィールドの開始値を設定(MySQL/PostgreSQL)
->invisible() SELECT *クエリに対しカラムを「不可視」にする(MySQL)
->nullable($value = true) NULL値をカラムに保存可能に設定
->storedAs($expression) stored generatedカラムを作成(MySQL/PostgreSQL)
->unsigned() INTEGERカラムをUNSIGNEDとして設定(MySQL)
->useCurrent() CURRENT_TIMESTAMPをデフォルト値として使用するようにTIMESTAMPカラムを設定
->useCurrentOnUpdate() レコードが更新されたときにCURRENT_TIMESTAMPを使用するようにTIMESTAMPカラムを設定(MySQL)
->virtualAs($expression) Virtual generatedカラムを生成(MySQL/PostgreSQL/SQLite)
->generatedAs($expression) 指定のシーケンスオプションで、識別カラムを生成(PostgreSQL)
->always() IDカラムの入力に対するシーケンス値の優先順位を定義(PostgreSQL)
->isGeometry() 空間カラムのタイプをgeometryに設定 - デフォルトタイプはgeography(PostgreSQL)

参考:
https://readouble.com/laravel/10.x/ja/migrations.html

Laravel11へアップデートする際の注意点

Laravel10から11のUpdateに伴って、「カラムを変更する場合、変更後もカラム定義を維持したいすべての修飾子を明示的に含める必要があります」となったため、より注意が必要です。

参考:
https://readouble.com/laravel/11.x/ja/upgrade.html#modifying-columns

GitHubで編集を提案

Discussion