본문 바로가기

Modern PHP

Laravel - DB 마이그레이션 (table 버전관리)


테이블 버전 관리

artisan CLI로 마이그레이션 만들기

$ php artisan make:migration create_posts_table
$ php artisan make:migration create_authors_table

database/migrations 폴더에 마이그레이션 파일 생성



해당 마이그레이션 파일에 실행과 롤백 코드 작성

class CreatePostsTable extends Migration
{
    public function up()
    {
        Schema::create('posts', function($table) {
            $table->increments('id'); // id INT AUTO_INCREMENT PRIMARY KEY
            $table->string('title', 100); // title VARCHAR(100)
            $table->text('body'); // body TEXT
            $table->timestamps(); // created_at TIMESTAMP, updated_at TIMESTAMP
        });
    }

    public function down()
    {
        Schema::dropIfExists('posts'); // DROP TABLE posts
    }
}


메소드 up()은 마이그레이션 실행 내용

메소드 down()은 롤백할 내용

$ php artisan migrate  # 실행
$ php artisan migrate:rollback  # 직전으로 롤백
$ php artisan migrate:reset  # DB 초기화
$ php artisan migrate:refresh  # 리셋 실행후 처음부터 마이그레이션 실행




필드 추가

테이블에 데이터가 있을 경우 필드 추가 마이그레이션 작성

$ php artisan make:migration add_name_to_authors_table
use Illuminate\Database\Schema\Blueprint;

class AddNameToAuthorsTable extends Migration
{
    public function up()
    {
        Schema::table('authors', function(Blueprint $table) {
            $table->string('name')->after('email')->nullable(); 
            // nullable()은 NULL 을 허용. name 필드 다음에 email 추가
        });
    }

    public function down()
    {
        Schema::table('authors', function(Blueprint $table) {
            $table->dropColumn('name');
        });
    }
}

Blueprint 의 풀 네임스페이스는 \Illuminate\Database\Schema\Blueprint 

코드 내에 두 군데 이상 같은 클래스가 쓰인다면 use 키워드로 import





'Modern PHP' 카테고리의 다른 글

Laravel - DB 쿼리 Facade & Eloquent ORM 발췌요약  (0) 2018.05.09