-
Notifications
You must be signed in to change notification settings - Fork 0
Migration
Tirapong Chaiyakun edited this page Sep 19, 2026
·
1 revision
ไฟล์อยู่ที่ Database/migrations/ ชื่อแบบ YYYYMMDDHHMMSS_create_users_table.php
php deawx make:migration create_users_table
php deawx migrate
php deawx migrate:status
php deawx migrate:rollback
php deawx migrate:fresh
php deawx db:tables
php deawx db:columns usersตารางที่รันแล้วถูกบันทึกใน migrations
<?php
declare(strict_types=1);
use Core\Blueprint;
use Core\Migration;
use Core\Schema;
return new class extends Migration {
public function up(): void
{
Schema::create('users', static function (Blueprint $table): void {
$table->id();
$table->string('email', 191)->unique();
$table->string('password', 255);
$table->timestamps();
});
}
public function down(): void
{
Schema::drop('users');
}
};up() รันตอน migrate
down() รันตอน rollback
| เมธอด | ความหมาย |
|---|---|
id() |
PK BIGINT auto increment ชื่อ id
|
id('user_id') |
PK ชื่ออื่น |
string('name', 255) |
VARCHAR |
text('body') |
TEXT |
integer('n') / bigInteger('n')
|
จำนวนเต็ม |
boolean('active') |
TINYINT(1) |
decimal('price', 10, 2) |
ทศนิยม |
timestamp('seen_at') |
TIMESTAMP |
timestamps() |
created_at และ updated_at
|
nullable() |
ว่างได้ |
unique() |
unique ที่คอลัมน์นั้น |
default('member') |
ค่าเริ่มต้น |
index() |
index ที่คอลัมน์ล่าสุด |
index('status') |
index ที่ระบุ |
index(['role', 'status']) |
composite index |
uniqueIndex('email') |
unique index |
foreignId('user_id', 'users') |
BIGINT + FK ไป users.id
|
foreign('user_id', 'users', 'id', 'CASCADE') |
FK เอง |
dropColumn('bio') |
ใช้กับ Schema::table
|
ON DELETE ที่รับได้: CASCADE, SET NULL, RESTRICT, NO ACTION
| เมธอด | ความหมาย |
|---|---|
Schema::create($table, $fn) |
สร้างตาราง ถ้ามีอยู่แล้วจะโยน error |
Schema::drop($table) |
ลบตาราง (ปิด FK ชั่วคราว) |
Schema::table($table, $fn) |
เพิ่มคอลัมน์ / index / FK หรือลบคอลัมน์ |
Schema::hasTable($table) |
มีตารางหรือไม่ |
Schema::hasColumn($table, $col) |
มีคอลัมน์หรือไม่ |
Schema::columns($table) |
รายชื่อฟิลด์จากฐานจริง |
Schema::tables() |
รายชื่อตารางทั้งหมด |
Schema::db() |
อินสแตนซ์ Medoo |
Schema::create ไม่เทียบ คอลัมน์ใน Blueprint กับตารางจริง เช็คแค่มีตารางหรือยัง
แก้ตารางที่มีอยู่แล้ว
Schema::table('users', static function (Blueprint $table): void {
$table->string('phone', 20)->nullable();
$table->index('phone');
});ทุก migration มี $this->db() เป็น Medoo
public function up(): void
{
$this->db()->create('notes', [
'id' => ['INT', 'NOT NULL', 'AUTO_INCREMENT', 'PRIMARY KEY'],
'title' => ['VARCHAR(191)', 'NOT NULL'],
]);
}วิธีที่แนะนำคือ Blueprint เพราะอ่านง่ายกว่า
โปรเจกต์มีไฟล์ตัวอย่าง 9 ตารางใน Database/migrations/
users → categories → tags → threads → posts → thread_tags → post_likes → attachments → reports
ยังไม่รันจนกว่าจะสั่ง php deawx migrate เอง