laravel column 변경 database migration 만들기

컬럼 변경

laravel 에서 개발할 경우 이미 생성한 컬럼의 타입이나 크기, null 여부 등을 변경할 경우가 있습니다.


DB 스키마 관리를 db migration 로 하고 있다면 변경 사항도 별도의 migration 을 생성하고 이 안에 변경 사항을 기술해 주어야 합니다.


예로 사용자 이름을 담는 name 컬럼을 10 자에서 20자 변경할 경우 다음과 같이 진행하면 됩니다.

$ php artisan --table users change_name_column_size_on_users_table


이제 migration 소스에서 다음과 같이 컬럼을 수정해 주면 됩니다.

	public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('name', 20)->change();
        });
    }


만약 컬럼의 null 여부를 not null 에서 nullable 로 바꾸거나 그 반대의 경우에는 다음과 같이 nullable(boolean) 을 호출한 후에 change() 메서드를 실행하면 됩니다.


public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->unsignedBigInteger('culture_resource_addinfo_id')->nullable(true)->change();
        });
    }


Constraint 가 있을 경우 


만약 참조 키(foreign key), unique 조건등 column에 constraint 가 있을 경우 삭제하면 무결성 제약에 의해서 에러 발생합니다.

 Illuminate\Database\QueryException  : SQLSTATE[HY000]: General error: 1832 Cannot change column 'author_id': used in a foreign key constraint 'books_author_id_foreign' (SQL: ALTER TABLE books CHANGE author_id author_id BIGINT UNSIGNED DEFAULT NULL)


이런 경우 변경이 매우 까다로와지며 참조 키가 있는 테이블을 참조 관계를 끊고 컬럼 유형을 먼저 바꾸는등의 작업을 해야 합니다.


주의해서 사용해야 하는  방법이만 이런 경우 migration 실행시 임시로 참조 무결성 확인을 끄고 실행후 다시 켜는 방법도 있습니다.

	public function up()
    {
        DB::statement('SET FOREIGN_KEY_CHECKS=0;');
        Schema::table('users', function (Blueprint $table) {
			 $table->unsignedBigInteger('culture_resource_addinfo_id')->nullable(true)->change();
		});
        DB::statement('SET FOREIGN_KEY_CHECKS=1;');
    }


같이 보기

Ref