Database migrate ของ Laravel เป็นการทำสคริปเพื่อ Generate ตาราง ให้เราผ่านคำสั่ง Laravel ที่เราเขียนขึ้นมา ซึ่งข้อดีช่วยให้ทำเราสามารถทำงานร่วมกันเป็นทีมได้ดียิ่งขึ้น ยกตัวอย่างให้เห็นภาพนะครับ เช่น ปกติเวลาเรา ทำงานมีการสร้าง ตารางใหม่หรือ อัพเดทฟิล์ดในตาราง ที่นี้เราก็ ไปใช้พวก phpmyadmin แล้ว copy script ส่งให้กันไปๆ มาๆ การทำงานหลายๆคนก็เริ่มลำบากละ เพราะว่า ต้องมานั่ง run script แล้วเผลอๆ บางคนลืม ทำสคริปส่งไปให้อีกทำให้ เกิดปัญหาขึ้นมา ดังนั้น Migrate จึงเกิดมาการนี้ ให้เหล่าโปรแกรมเมอร์ เวลาต้องการสร้างหรือแก้ไขตาราง ก็มาเขียนคำสั่ง (PHP) แล้ว Generate เอา ทำให้ เวลาคนอื่น มาทำงานต่อก็เพียงแค่ Pull code จาก เพื่อนแล้ว ก็ run migrate เป็นอันจบแล้ว ได้ฐานข้อมูลล่าสุด พร้อมเขียนโค๊ด ได้ทันที
สำหรับบทความนี้ ผมมาสอนวิธีใช้งานกันนะครับ
Case study: สร้างตาราง orders
โดยมีฟิล์ดดังนี้
id (int), name (varchar 100), email (varchar 100), tel (varchar 20), detail (text)
ให้เราเปิด command line ขึ้นมานะครับ แล้วพิมพ์คำสั่ง สร้างไฟล์ migration
1 |
php artisan make:migration create_orders_table |
หลังจากเราสร้างมาแล้ว ให้เรา เขียน code migrate ดังนี้
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateOrdersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('orders', function (Blueprint $table) { $table->bigIncrements('id'); $table->string('name', 100); $table->string('email', 100); $table->string('tel', 20)->nullable(); $table->text('detail')->nullable(); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('orders'); } } |
เมื่อเขียนคำสั่ง migrate เรียบร้อยให้เรา run command
1 |
php artisan migrate |
แล้วกลับไปดู ฐานข้อมูล ของเรา จะเห็นว่ามีการเพิ่มตาราง มาแล้ว
ทั้งนี้เรายังสามารถ Rollback migration ของเราที่ทำมาด้วยคำสั่ง
1 |
php artisan migrate:rollback |
หรือต้องการ rollback กลับไปยังขั้นตอนใดขั้นตอนหนึ่งก็ใช้คำสั่ง
1 |
php artisan migrate:rollback --step=5 |
เรามาดูคำสั่งแต่ละคำสั่งของ migrate
ตาราง(Tables)
สร้างตาราง
1 2 3 |
Schema::create('orders', function (Blueprint $table) { //code } |
เปลี่ยนชื่อตาราง
1 |
Schema::rename($from, $to); |
ลบตาราง
1 |
Schema::drop('users'); |
คอลัมน์(Columns)
หลังจากเรามีการสร้างตารางมาแล้วให้เราเขียนคำสั่ง สร้าง columns ลงในตารางภายใน Schema::table ฟังก์ชั่น
สร้างคอลัมน์
1 2 3 |
Schema::table('users', function (Blueprint $table) { $table->string('email'); }); |
จะเห็นว่าเราจะสามารถกำหนดประเภทคอลัมน์ได้ว่า เป็นอะไร จากตัวอย่างเป็น string (varchar) มาดูว่าประเภท คอลัมน์ที่มีให้ใส่มีอะไรบ้าง
ประเภทคอลัมน์ที่สามารถกำหนดได้
Command | Description |
---|---|
$table->id(); |
Alias of $table->bigIncrements('id') . |
$table->foreignId('user_id'); |
Alias of $table->unsignedBigInteger('user_id') . |
$table->bigIncrements('id'); |
Auto-incrementing UNSIGNED BIGINT (primary key) equivalent column. |
$table->bigInteger('votes'); |
BIGINT equivalent column. |
$table->binary('data'); |
BLOB equivalent column. |
$table->boolean('confirmed'); |
BOOLEAN equivalent column. |
$table->char('name', 100); |
CHAR equivalent column with a length. |
$table->date('created_at'); |
DATE equivalent column. |
$table->dateTime('created_at', 0); |
DATETIME equivalent column with precision (total digits). |
$table->dateTimeTz('created_at', 0); |
DATETIME (with timezone) equivalent column with precision (total digits). |
$table->decimal('amount', 8, 2); |
DECIMAL equivalent column with precision (total digits) and scale (decimal digits). |
$table->double('amount', 8, 2); |
DOUBLE equivalent column with precision (total digits) and scale (decimal digits). |
$table->enum('level', ['easy', 'hard']); |
ENUM equivalent column. |
$table->float('amount', 8, 2); |
FLOAT equivalent column with a precision (total digits) and scale (decimal digits). |
$table->geometry('positions'); |
GEOMETRY equivalent column. |
$table->geometryCollection('positions'); |
GEOMETRYCOLLECTION equivalent column. |
$table->increments('id'); |
Auto-incrementing UNSIGNED INTEGER (primary key) equivalent column. |
$table->integer('votes'); |
INTEGER equivalent column. |
$table->ipAddress('visitor'); |
IP address equivalent column. |
$table->json('options'); |
JSON equivalent column. |
$table->jsonb('options'); |
JSONB equivalent column. |
$table->lineString('positions'); |
LINESTRING equivalent column. |
$table->longText('description'); |
LONGTEXT equivalent column. |
$table->macAddress('device'); |
MAC address equivalent column. |
$table->mediumIncrements('id'); |
Auto-incrementing UNSIGNED MEDIUMINT (primary key) equivalent column. |
$table->mediumInteger('votes'); |
MEDIUMINT equivalent column. |
$table->mediumText('description'); |
MEDIUMTEXT equivalent column. |
$table->morphs('taggable'); |
Adds taggable_id UNSIGNED BIGINT and taggable_type VARCHAR equivalent columns. |
$table->uuidMorphs('taggable'); |
Adds taggable_id CHAR(36) and taggable_type VARCHAR(255) UUID equivalent columns. |
$table->multiLineString('positions'); |
MULTILINESTRING equivalent column. |
$table->multiPoint('positions'); |
MULTIPOINT equivalent column. |
$table->multiPolygon('positions'); |
MULTIPOLYGON equivalent column. |
$table->nullableMorphs('taggable'); |
Adds nullable versions of morphs() columns. |
$table->nullableUuidMorphs('taggable'); |
Adds nullable versions of uuidMorphs() columns. |
$table->nullableTimestamps(0); |
Alias of timestamps() method. |
$table->point('position'); |
POINT equivalent column. |
$table->polygon('positions'); |
POLYGON equivalent column. |
$table->rememberToken(); |
Adds a nullable remember_token VARCHAR(100) equivalent column. |
$table->set('flavors', ['strawberry', 'vanilla']); |
SET equivalent column. |
$table->smallIncrements('id'); |
Auto-incrementing UNSIGNED SMALLINT (primary key) equivalent column. |
$table->smallInteger('votes'); |
SMALLINT equivalent column. |
$table->softDeletes('deleted_at', 0); |
Adds a nullable deleted_at TIMESTAMP equivalent column for soft deletes with precision (total digits). |
$table->softDeletesTz('deleted_at', 0); |
Adds a nullable deleted_at TIMESTAMP (with timezone) equivalent column for soft deletes with precision (total digits). |
$table->string('name', 100); |
VARCHAR equivalent column with a length. |
$table->text('description'); |
TEXT equivalent column. |
$table->time('sunrise', 0); |
TIME equivalent column with precision (total digits). |
$table->timeTz('sunrise', 0); |
TIME (with timezone) equivalent column with precision (total digits). |
$table->timestamp('added_on', 0); |
TIMESTAMP equivalent column with precision (total digits). |
$table->timestampTz('added_on', 0); |
TIMESTAMP (with timezone) equivalent column with precision (total digits). |
$table->timestamps(0); |
Adds nullable created_at and updated_at TIMESTAMP equivalent columns with precision (total digits). |
$table->timestampsTz(0); |
Adds nullable created_at and updated_at TIMESTAMP (with timezone) equivalent columns with precision (total digits). |
$table->tinyIncrements('id'); |
Auto-incrementing UNSIGNED TINYINT (primary key) equivalent column. |
$table->tinyInteger('votes'); |
TINYINT equivalent column. |
$table->unsignedBigInteger('votes'); |
UNSIGNED BIGINT equivalent column. |
$table->unsignedDecimal('amount', 8, 2); |
UNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits). |
$table->unsignedInteger('votes'); |
UNSIGNED INTEGER equivalent column. |
$table->unsignedMediumInteger('votes'); |
UNSIGNED MEDIUMINT equivalent column. |
$table->unsignedSmallInteger('votes'); |
UNSIGNED SMALLINT equivalent column. |
$table->unsignedTinyInteger('votes'); |
UNSIGNED TINYINT equivalent column. |
$table->uuid('id'); |
UUID equivalent column. |
$table->year('birth_year'); |
YEAR equivalent column. |
**ข้อมูลตารางประเภทคอลัมน์นำมาจาก https://laravel.com/docs
Option เพิ่มเติมของคอลัมน์ (Column Modifiers)
เช่นถ้าต้องการให้ column A สามารถว่างได้ สามารถเขียนได้ตาม code ด้านล่างนี้
1 2 3 |
Schema::table('users', function (Blueprint $table) { $table->string('email')->nullable(); }); |
ซึ่ง option ของ column มีตามรายการ ด้านล่างนี้
Modifier | Description |
---|---|
->after('column') |
ทำการวางคอลัมน์ไว้หลัง ‘column’ (สำหรับ MySQL) |
->autoIncrement() |
เซ็ต Integer ให้กับ auto-increment ให้กับคอลัมน์ พร้อมทั้งเป็น Primary key |
->charset('utf8mb4') |
ระบุ character ให้กับคอลัมน์ (สำหรับ MySQL) |
->collation('utf8mb4_unicode_ci') |
ระบุ collation (MySQL/PostgreSQL/SQL Server) |
->comment('my comment') |
ใส่ comment ให้กับคอลัมน์ได้ |
->default($value) |
ระบุค่า “default” ให้กับคอลัมน์ |
->first() |
วางคอลัมน์ไว้ลำดับแรกของตาราง (MySQL) |
->nullable($value = true) |
สามารถให้คอลัมน์สามารถระบุค่าว่าง(null) ได้ |
->storedAs($expression) |
สร้าง stored generated ให้กับคอลัมน์ (MySQL) |
->unsigned() |
เซ็ตคอลัมน์ที่เป็น type integer ให้ UNSIGNED (MySQL) |
->useCurrent() |
เซ็ตคอลัมน์ที่เป็น type TIMESTAMP ให้ CURRENT_TIMESTAMP เป็น default |
->virtualAs($expression) |
สร้าง virtual generated (MySQL) |
->generatedAs($expression) |
สร้าง identity กับ ระบุ sequence options ให้กับคอลัมน์ (PostgreSQL) |
->always() |
กำหนดความสำคัญของค่าตามลำดับ input (PostgreSQL) |
**ข้อมูลตารางประเภทคอลัมน์นำมาจาก https://laravel.com/docs
แก้ไขคอลัมน์
เราสามารถแก้ไขคอลัมน์โดยการใส่ code ดังนี้
1 2 3 |
Schema::table('users', function (Blueprint $table) { $table->string('name', 50)->change(); }); |
แต่การใช้คำสั่งแก้ไขเราต้องติดตั้ง composer ก่อน โดย run comman line ดังนี้
1 |
composer require doctrine/dbal |
ลบคอลัมน์
เราสามารถลบคอลัมน์โดยการใส่ code ดังนี้
1 2 3 |
Schema::table('users', function (Blueprint $table) { $table->dropColumn('votes'); }); |
ตั้งค่า Indexes
ใน migration เราสามารถตั้งค่า index ให้กับคอลัมน์ได้ เช่น unique(), index(), primary() โดยดูตัวอย่างจาก code ดังนี้
1 2 3 4 |
$table->primary('id'); $table->primary(['id', 'parent_id']); //ตั้ง primary key หลายๆคอลัมน์ $table->unique('email'); $table->index('state'); |
เราลองมาดูแบบ full code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
<?php use Illuminate\Database\Migrations\Migration; use Illuminate\Database\Schema\Blueprint; use Illuminate\Support\Facades\Schema; class CreateOrdersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('orders', function (Blueprint $table) { $table->integer('id'); $table->string('name', 100); $table->string('email', 100); $table->string('tel', 20)->nullable(); $table->text('detail')->nullable(); $table->timestamps(); $table->primary('id'); $table->unique('email'); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::dropIfExists('orders'); } } |
สำหรับบทความ migration จบเพีงเท่านี้หากใครมีข้อสงสัยหรือคำถามใดๆ สามารถ comment มาได้ครับ
ขอบคุณครับ