Laravel – EP12 Database กับการทำ Migration

สอน Laravel

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

หลังจากเราสร้างมาแล้ว ให้เรา เขียน code migrate ดังนี้

เมื่อเขียนคำสั่ง migrate เรียบร้อยให้เรา run command

แล้วกลับไปดู ฐานข้อมูล ของเรา จะเห็นว่ามีการเพิ่มตาราง มาแล้ว
Laravel Migrate

ทั้งนี้เรายังสามารถ Rollback migration ของเราที่ทำมาด้วยคำสั่ง

หรือต้องการ rollback กลับไปยังขั้นตอนใดขั้นตอนหนึ่งก็ใช้คำสั่ง

เรามาดูคำสั่งแต่ละคำสั่งของ migrate

ตาราง(Tables)

สร้างตาราง

เปลี่ยนชื่อตาราง

ลบตาราง

คอลัมน์(Columns)

หลังจากเรามีการสร้างตารางมาแล้วให้เราเขียนคำสั่ง สร้าง columns ลงในตารางภายใน Schema::table ฟังก์ชั่น 

สร้างคอลัมน์

จะเห็นว่าเราจะสามารถกำหนดประเภทคอลัมน์ได้ว่า เป็นอะไร จากตัวอย่างเป็น 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 ด้านล่างนี้

ซึ่ง 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 ดังนี้

แต่การใช้คำสั่งแก้ไขเราต้องติดตั้ง composer ก่อน โดย run comman line ดังนี้

ลบคอลัมน์

เราสามารถลบคอลัมน์โดยการใส่ code ดังนี้

ตั้งค่า Indexes

ใน migration เราสามารถตั้งค่า index ให้กับคอลัมน์ได้ เช่น unique(), index(), primary() โดยดูตัวอย่างจาก code ดังนี้

เราลองมาดูแบบ full code

สำหรับบทความ migration จบเพีงเท่านี้หากใครมีข้อสงสัยหรือคำถามใดๆ สามารถ comment มาได้ครับ

You May Also Like

About the Author: Onmobile

โปรแกรมเมอร์
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
kunatip
kunatip
4 years ago

ขอบคุณครับ