0
0

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 1 year has passed since last update.

LaravelのマイグレーションでCHECK制約を設定する方法

Posted at

はじめに

タイトル通りにはなりますが、LaravelのマイグレーションでCHECK制約を設定する方法について書いています。

CHECK制約とは

SQLで使える制約で、データを追加・更新する際、指定した条件を満たさない場合はデータを保存できないようにするものです。
例えば年齢を保存するカラムに対して18以上しか保存できないようにするなどの使い方があります。

前提

  • Laravel:9.24.0
  • PHP:8.1.13
  • MySQL:8.0.31

設定方法

まずはマイグレーションファイルを作成します。

php artisan make:migration create_users_table

マイグレーションファイルの中でDBファザードのstatementメソッドを使ってCHECK制約を設定します。
statementは引数にSQL文を入れて実行することができます。

<?php

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

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('age');
            $table->string('phone_number')->unique()->nullable();
            $table->string('email')->unique()->nullable();
            $table->string('password');
        });

        // ageが18以上であるかどうかをチェックする
        Schema::table('users', function (Blueprint $table) {
            DB::statement('ALTER TABLE users ADD CONSTRAINT check_age_over_eighteen CHECK (age >= 18);');
        });

        // phone_numberかemailのうち、少なくともどちらか一方はNULLでないことをチェックする
        Schema::table('users', function (Blueprint $table) {
            DB::statement(
                'ALTER TABLE users ADD CONSTRAINT check_required_phone_number_or_email
                CHECK (phone_number IS NOT NULL OR email IS NOT NULL);'
            );
        });
    }
    
    public function down()
    {
        Schema::dropIfExists('users');
    }
}

CHECK制約は下記のように設定します。

ALTER TABLE { テーブル名 } ADD CONSTRAINT { 制約名 } CHECK ({ 制約 });

以上になります。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?