관리 메뉴

java,javascript,android,php,sql,공부용,메모용

라라벨9 - 마이그레이션 정리 본문

개발/php

라라벨9 - 마이그레이션 정리

yy_dd2 2026. 3. 18. 17:58
반응형

라라벨9 - 마이그레이션 정리

 

“왜 마이그레이션을 사용하나요?” 

마이그레이션은 “DB 테이블 구조를 코드로 관리하기 위한 기능”

 


1. 마이그레이션 파일 생성

sail artisan make:migration create_authors_table --create=authors
  • --create=테이블명 : 신규 테이블 생성 코드 자동 포함

2. 마이그레이션 파일 생성 예시

sail artisan make:migration create_authors_table --create=authors
sail artisan make:migration create_publishers_table --create=publishers
sail artisan make:migration create_books_table --create=books
sail artisan make:migration create_bookdetails_table --create=bookdetails

or

sail artisan make:migration create_authors_table
sail artisan make:migration create_publishers_table
sail artisan make:migration create_books_table
sail artisan make:migration create_bookdetails_table

생성 파일 예시:

2026_03_18_071744_create_authors_table.php
2026_03_18_071817_create_publishers_table.php
2026_03_18_071846_create_books_table.php
2026_03_18_071913_create_bookdetails_table.php

✔️ --create 옵션 차이

 
sail artisan make:migration create_authors_table

→ 이름을 보고 Laravel이 자동으로 테이블 생성 코드 추가

sail artisan make:migration create_authors_table --create=authors

→ 테이블명을 명시적으로 지정


✔️ 왜 옵션 없이도 되나요?

create_테이블명_table 형식이면
Laravel이 자동으로 Schema::create() 생성


✔️ 언제 옵션이 필요하나요?

  • 이름이 애매할 때
  • create 형식이 아닐 때

✔️ 한 줄 정리

--create는 필수가 아니라,
Laravel이 못 알아볼 때 쓰는 옵션


3. 테이블 정의

1) authors 테이블

컬럼타입설명

id bigint 기본키
name string(100) 저자명
created_at timestamp 생성일시
updated_at timestamp 수정일시

2) publishers 테이블

컬럼타입설명

id bigint 기본키
isbn string(100) ISBN
address text 주소
created_at timestamp 생성일시
updated_at timestamp 수정일시

3) bookdetails 테이블

컬럼타입설명

id bigint 기본키
name string(100) 책 이름
book_id integer 책 ID
isbn string(100) ISBN
published_date date 출판일
price integer 가격
created_at timestamp 생성일시
updated_at timestamp 수정일시

 

 

timestamps()는 created_at, updated_at을 자동 생성

 

// authors 테이블
<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('authors', function (Blueprint $table) {
            $table->id();
            $table->string('name', '100');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('authors');
    }
};
// publishers 테이블
<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('publishers', function (Blueprint $table) {
            $table->id();
            $table->string('isbn', '100');
            $table->text('address');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('publishers');
    }
};
// bookdetails 테이블
<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('bookdetails', function (Blueprint $table) {
            $table->id();
            $table->string('name', '100');
            $table->integer('book_id');
            $table->string('isbn', '100');
            $table->date('published_date');
            $table->integer('price');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('bookdetails');
    }
};

 

 


4. 테이블 삭제 처리

public function down(): void
{
    Schema::dropIfExists('bookdetails');
}
  • 롤백 시 테이블 삭제

5. 컬럼 타입 / 스키마 빌더

타입작성 방법설명

string $table->string('name', 100); 문자열
integer $table->integer('price'); 정수
boolean $table->boolean('flag'); 참/거짓
text $table->text('content'); 긴 문자열
date $table->date('published_date'); 날짜
timestamp $table->timestamp('created_at'); 시간

6. 컬럼 속성 메서드

메서드설명

->nullable() NULL 허용
->default(값) 기본값 설정
->unsigned() 양수만 허용
->after('컬럼') 특정 컬럼 뒤에 배치 (MySQL)

예시

$table->string('name', 50)->nullable();
$table->integer('price')->default(0);
$table->integer('count')->unsigned();

7. 인덱스 관련

1) 컬럼 정의 시 인덱스 부여

메서드설명
$table->string('email')->unique(); 유니크 인덱스
$table->string('name')->index(); 일반 인덱스
$table->id(); 기본키 자동 생성

예시

 
$table->string('email')->unique();
$table->string('name')->index();
 

2) 별도로 인덱스 부여 (나눠서 작성)

메서드설명
$table->primary('id'); 기본키 지정
$table->unique('email'); 유니크 인덱스
$table->index('name'); 일반 인덱스

예시

 
$table->string('email');
$table->unique('email');

$table->string('name');
$table->index('name');
 

3) 인덱스 삭제

메서드설명
$table->dropPrimary('users_primary'); 기본키 삭제
$table->dropUnique('users_email_unique'); 유니크 인덱스 삭제
$table->dropIndex('users_name_index'); 일반 인덱스 삭제

예시

 
$table->dropPrimary('users_primary');
$table->dropUnique('users_email_unique');
$table->dropIndex('users_name_index');
 

✔️ 추가로 중요한 포인트 (짧게)

인덱스는
“컬럼 작성할 때 같이 붙일 수도 있고”
“나중에 따로 지정할 수도 있다”


8. 마이그레이션 실행 / 롤백

sail artisan migrate

테이블 생성 실행

sail artisan migrate:rollback

최근 마이그레이션 취소

sail artisan migrate:reset

전체 롤백

sail artisan migrate:refresh

전체 롤백 후 재실행

 

마이그레이션 실행 시 오류

 

  • php artisan migrate → ❌
  • sail artisan migrate → ✅

2026.03.18 - [개발/php] - 라라벨8 - Laravel Sail에서 php artisan migrate 오류 해결 방법 (mysql 연결 실패)

 

라라벨8 - Laravel Sail에서 php artisan migrate 오류 해결 방법 (mysql 연결 실패)

[Laravel + Sail] php artisan migrate 오류 해결 방법 (mysql 연결 실패)✔️ 결론 (가장 중요)Laravel Sail(Docker 환경)을 사용하는 경우php artisan이 아니라 반드시 sail artisan으로 실행해야 합니다sail artisan migrate

tog-code.tistory.com

 

 


9. 실행 상태 확인

sail mysql
SELECT * FROM migrations;

예상 결과

+----+----------------------------------------+-------+
| id | migration                             | batch |
+----+----------------------------------------+-------+
| 1  | 2026_03_18_071744_create_authors_table | 1     |
| 2  | 2026_03_18_071817_create_publishers_table | 1  |
| 3  | 2026_03_18_071846_create_books_table   | 1     |
| 4  | 2026_03_18_071913_create_bookdetails_table | 1  |
+----+----------------------------------------+-------+
  • 실행된 마이그레이션 기록 관리 테이블

한 줄 정리

마이그레이션은 “테이블 구조를 코드로 관리하고 실행/롤백까지 가능한 기능”

 

 

1. 마이그레이션 파일 생성
2. 컬럼 정의
3. migrate 실행
4. 필요시 rollback

반응형
Comments