Skip to content

🗄️ Models & Database

Laravel ทำให้การจัดการฐานข้อมูลเป็นเรื่องง่ายด้วย Eloquent ORM (Object-Relational Mapper) ซึ่งช่วยให้เราเขียนโค้ด PHP แทนคำสั่ง SQL ยาวๆ ได้


🏗️ 1. Migrations (การสร้างตาราง)

Migrations เปรียบเหมือน Version Control ของฐานข้อมูล ช่วยให้ทีมมีโครงสร้าง Database ที่ตรงกันเสมอ

สร้าง Model พร้อม Migration

bash
php artisan make:model Product -m

Flag -m จะสร้างไฟล์ Migration ให้ด้วยใน database/migrations/

ตัวอย่างไฟล์ Migration

แก้ไขไฟล์ database/migrations/xxxx_xx_xx_create_products_table.php:

php
public function up(): void
{
    Schema::create('products', function (Blueprint $table) {
        $table->id(); // Auto-increment ID
        $table->string('name');
        $table->text('description')->nullable();
        $table->decimal('price', 8, 2); // 999,999.99
        $table->integer('stock')->default(0);
        $table->timestamps(); // create_at, updated_at
    });
}

รัน Migration

เพื่อสร้างตารางจริงใน Database ให้รันคำสั่ง:

bash
php artisan migrate

🧠 2. Eloquent Model

Model คือตัวแทนของตารางใน Database (เช่น Model User แทนตาราง users)

ตั้งค่า Fillable (Mass Assignment)

เพื่อความปลอดภัย เราต้องกำหนดว่า field ไหนอนุญาตให้กรอกข้อมูลได้ผ่านคำสั่ง create() หรือ update()

ไฟล์ app/Models/Product.php:

php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    // อนุญาตให้แก้ไข field เหล่านี้ได้
    protected $fillable = [
        'name',
        'description',
        'price',
        'stock'
    ];
}

🔍 3. การใช้งานพื้นฐาน (CRUD)

ตัวอย่างการเรียกใช้ Model ใน Controller:

Create (สร้างข้อมูล)

php
Product::create([
    'name' => 'iPhone 15',
    'price' => 32900
]);

Read (อ่านข้อมูล)

php
// ดึงทั้งหมด
$products = Product::all();

// ดึงตาม ID (ถ้าไม่เจอจะ Error 404 ให้เอง)
$product = Product::findOrFail(1);

// ค้นหาด้วยเงื่อนไข
$cheapProducts = Product::where('price', '<', 1000)->get();

Update (แก้ไขข้อมูล)

php
$product = Product::find(1);
$product->update(['price' => 29900]);

Delete (ลบข้อมูล)

php
$product = Product::find(1);
$product->delete();

🔗 4. Relationships (ความสัมพันธ์)

Eloquent จัดการความสัมพันธ์ระหว่างตารางได้ง่ายมาก เช่น User มีหลาย Order (One-to-Many)

ไฟล์ app/Models/User.php:

php
public function orders()
{
    return $this->hasMany(Order::class);
}

ไฟล์ app/Models/Order.php:

php
public function user()
{
    return $this->belongsTo(User::class);
}

การใช้งาน:

php
// ดึง orders ทั้งหมดของ user คนที่ 1
$orders = User::find(1)->orders;

// ดึง user เจ้าของ order นี้
$user = Order::find(1)->user;

🌱 5. Seeding (ข้อมูลจำลอง)

เราสามารถสร้างข้อมูลตัวอย่างไว้ทดสอบระบบได้

  1. สร้าง Seeder: php artisan make:seeder ProductSeeder
  2. เขียนโค้ดเพิ่มข้อมูลในไฟล์ Seeder
  3. รันคำสั่ง: php artisan db:seed

(แนะนำให้ใช้ Model Factory คู่กันเพื่อสร้างข้อมูลจำนวนมากแบบสุ่ม)