PHP Laravel 6 – CRUD 기본 with mysql – 테이블 생성 (1)

$> php artisan –version

Laravel Framework 6.9.0

1. 테이블 생성 및 모델 파일 생성
- 생성에 앞서 ".env" 파일에 자신이 사용 하는 DB 에 맞게 설정한다. 

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test_db
DB_USERNAME=test_user
DB_PASSWORD=test_passwd

- 실행 1 : 파일생성
$> php artisan make:model TestCRUD -m
Model created successfully.
Created Migration: 2020_01_03_011220_create_test_c_r_u_d_s_table

- 확인 1 : 생성된 파일 for DB 테이블
$> cd /database/migrations
2020_01_03_011220_create_test_c_r_u_d_s_table.php

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

classCreateTestCRUDSTableextendsMigration

{

/**

     * Run the migrations.

     *

     * @return void

     */

publicfunctionup()

    {

Schema::create(‘test_c_r_u_d_s’, function (Blueprint$table) {

$table->bigIncrements(‘id’);

$table->timestamps();

        });

    }

/**

     * Reverse the migrations.

     *

     * @return void

     */

publicfunctiondown()

    {

Schema::dropIfExists(‘test_c_r_u_d_s’);

    }

}

위 내용을 아래와 같이 변경 하자 
변경내용은 
- 테이블에 추가되는 컬럼 추가 
            $table->string('title', 100);
            $table->text('description')->nullable();
- 테이블명 변경
            test_c_r_u_d_s => test_tab

<?php

use Illuminate\Database\Migrations\Migration;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Support\Facades\Schema;

classCreateTestCRUDSTableextendsMigration

{

/**

     * Run the migrations.

     *

     * @return void

     */

publicfunctionup()

    {

Schema::create(‘test_tab’, function (Blueprint$table) {

$table->bigIncrements(‘id’);

$table->string(‘title’, 100);

$table->text(‘description’)->nullable();

$table->timestamps();

        });

    }

/**

     * Reverse the migrations.

     *

     * @return void

     */

publicfunctiondown()

    {

Schema::dropIfExists(‘test_tab‘);

    }

}

– 실행 2 : 테이블 생성

$> php artisan migrate

Migrating: 2020_01_03_011220_create_test_c_r_u_d_s_table

Migrated:  2020_01_03_011220_create_test_c_r_u_d_s_table (0.11 seconds)

– 확인 2 : 생성된 테이블

– 확인 3 :생성된 모델 파일 
$> cd /app
TestCRUD.php 

– 모델 파일 편집

<?php

namespaceApp;

use Illuminate\Database\Eloquent\Model;

classTestCRUDextendsModel

{

//

}

편집 아래  

<?php

namespaceApp;

use Illuminate\Database\Eloquent\Model;

classTestCRUDextendsModel

{

protected $table = ‘test_tab’;    // 설명의 편의와 이해를 돕고자 default table name 변경
// ( Default table 경우 해당 라인은 사용 하지 않아도 된다 )

protected $fillable = [‘title’, ‘description’];

}

답글 남기기

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다