[Laravel] Migrations

[Laravel] Migrations updated_at: 2024-07-18 18:41

Migrations

마이그레이션은 생성, 변경, 삭제된 database를 파일로 교환함으로서 다른 작업자간에 table을 공유할 수 있는 것이 장점입니다.

마이그레이션 관련 참조;

기본 형태

migration의 가장 기본적인 형태는 아래와 같습니다.
up 메소드는 새로운 테이블, 컬럼 혹은 인덱스등을 데이타 베이스에 추가시킬때 사용하며
down 메소드는 up 메소드에서 실행된 기능의 반대 기능을 가지게 됩니다.
아래처럼 up 메소드에서 create를 하였다면 down에서는 drop을 하여야 합니다.

...........
return new class extends Migration
{
  public function up(): void
  {
    Schema::create('flights', function (Blueprint $table) { //
    // ...
    });
  }

  public function down(): void
  {
    Schema::drop('flights');
  }
};

connection

어플리케이션에 설정된 기본 데이타베이스 커넥션과 다를 경우 아래처럼 처리하면 됩니다.

protected $connection = 'pgsql';

Running Migrations 실행

php artisan migrate

rollback

롤백을 할경우는 매우 세심한 주의가 필요하다. 잘못할 경우 모든 테이블 및 데이타가 날아갈 수 있으므로 주의해야 한다. 가장 최근의 마이그레이션 데이타를 롤백한다.

php artisan migrate:rollback

Determining Table / Column Existence

if (Schema::hasTable('users')) {
  // The "users" table exists...
}
 
if (Schema::hasColumn('users', 'email')) {
  // The "users" table exists and has an "email" column...
}
 
if (Schema::hasIndex('users', ['email'], 'unique')) {
  // The "users" table exists and has a unique index on the "email" column...
}

Columns

id()

id()는 bigIncrements 와 동일한 메소드이다.

$table->id();
평점을 남겨주세요
평점 : 2.5
총 투표수 : 1

질문 및 답글