メインコンテンツへ移動

เนื้อหาภาษาไทย / タイ語のコンテンツ

システムガイド 内容確認済み

การสร้าง Entity: Mapping Object กับ Table

บทความนี้อธิบายถึงการสร้าง Entity Class ใน Doctrine ORM ซึ่งเปรียบเสมือนตัวแทนของตารางในฐานข้อมูล เพื่อให้สามารถจัดการข้อมูลผ่านโค้ด PHP ได้ง่ายขึ้น โดยใช้ Anno...

การสร้าง Entity: Mapping Object กับ Table

หลังจากที่เราได้ทำการติดตั้งและตั้งค่า Doctrine ORM ในบทที่แล้ว (ถ้ายังไม่ได้อ่าน ย้อนกลับไปอ่านบทที่ 3 ก่อนนะครับ) ถึงเวลาที่เราจะเริ่มสร้างสิ่งที่เรียกว่า "Entity" กันแล้ว Entity คืออะไร? Entity ในโลกของ ORM ก็เปรียบเสมือนตัวแทนของตาราง (Table) ในฐานข้อมูลของเรานั่นเอง มันเป็น Object ที่เราใช้ในการจัดการข้อมูลในฐานข้อมูลผ่านโค้ด PHP ของเรา โดยไม่ต้องเขียน SQL เองให้ปวดหัว

ในบทนี้ เราจะมาเรียนรู้วิธีการสร้าง Entity Class และการ Mapping Field (คุณสมบัติของ Object) กับ Column (คอลัมน์ในตาราง) ในฐานข้อมูลกันครับ

Entity Class คืออะไร?

Entity Class ก็คือ Class PHP ธรรมดาๆ นี่แหละครับ แต่เราจะใช้ Annotations หรือ Attributes (ขึ้นอยู่กับเวอร์ชันของ PHP และ ORM Framework ที่ใช้) เพื่อบอกให้ ORM รู้ว่า Class นี้เป็น Entity และ Field แต่ละตัวใน Class นี้ Mapping กับ Column ไหนในตารางฐานข้อมูล

**ตัวอย่าง:** สมมติว่าเรามีตาราง `products` ในฐานข้อมูลของเรา ซึ่งมี Column ดังนี้:

  • `id` (INT, Primary Key, Auto-Increment)
  • `name` (VARCHAR)
  • `description` (TEXT)
  • `price` (DECIMAL)

เราจะสร้าง Entity Class ที่ชื่อว่า `Product` เพื่อเป็นตัวแทนของตารางนี้:

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="products")
 */
class Product
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $description;

    /**
     * @ORM\Column(type="decimal", precision=10, scale=2)
     */
    private $price;

    // Getters and Setters (จะอธิบายในภายหลัง)
}

**คำอธิบาย:**

  • `namespace App\Entity;`: บอกว่า Class นี้อยู่ใน Namespace `App\Entity` ซึ่งเป็น convention ที่ใช้กันทั่วไปในการจัดระเบียบโค้ด
  • `use Doctrine\ORM\Mapping as ORM;`: Import Class `Mapping` จาก Doctrine ORM เพื่อใช้ Annotations ต่างๆ
  • `@ORM\Entity`: Annotation นี้บอกว่า Class `Product` เป็น Entity
  • `@ORM\Table(name="products")`: Annotation นี้บอกว่า Entity นี้ Mapping กับตารางชื่อ `products` ในฐานข้อมูล

Annotations/Attributes

Annotations (หรือ Attributes ใน PHP 8+) คือ Metadata ที่เราใช้เพื่อบอกข้อมูลเพิ่มเติมเกี่ยวกับ Class, Property, หรือ Method ให้กับ ORM Framework Annotations จะอยู่ในรูปแบบ `/** @AnnotationName(parameters) */` ส่วน Attributes จะอยู่ในรูปแบบ `#[AttributeName(parameters)]` (ตัวอย่างเช่น `#ORM\Entity`) ทั้งสองอย่างทำหน้าที่เหมือนกัน แต่ Attributes เป็น syntax ที่ใหม่กว่าและอ่านง่ายกว่า

ในตัวอย่างข้างต้น เราใช้ Annotations หลายตัวเพื่อ Mapping Field กับ Column:

  • `@ORM\Id`: บอกว่า Field นี้เป็น Primary Key
  • `@ORM\GeneratedValue`: บอกว่า Field นี้เป็น Auto-Increment (ค่าจะถูกสร้างขึ้นโดยอัตโนมัติโดยฐานข้อมูล)
  • `@ORM\Column(type="...", ...)`: บอกว่า Field นี้ Mapping กับ Column ในตาราง และกำหนด Data Type และ Constraints อื่นๆ

**ประเภทของ Data Type ที่พบบ่อย:**

  • `integer`: จำนวนเต็ม
  • `string`: ข้อความ
  • `text`: ข้อความยาวๆ
  • `boolean`: ค่าจริงหรือเท็จ
  • `decimal`: จำนวนทศนิยม
  • `datetime`: วันที่และเวลา
  • `date`: วันที่
  • `time`: เวลา

**Options อื่นๆ ที่ใช้กับ `@ORM\Column`:**

  • `length`: ความยาวสูงสุดของ String (เช่น `length=255`)
  • `nullable`: อนุญาตให้เป็นค่า `NULL` ได้หรือไม่ (เช่น `nullable=true`)
  • `unique`: กำหนดให้ Column นี้มีค่า Unique เท่านั้น (เช่น `unique=true`)
  • `precision`: จำนวนหลักทั้งหมดสำหรับ Decimal (เช่น `precision=10`)
  • `scale`: จำนวนหลักหลังจุดทศนิยมสำหรับ Decimal (เช่น `scale=2`)

Mapping Field กับ Column

การ Mapping Field กับ Column คือการบอกให้ ORM รู้ว่า Field แต่ละตัวใน Entity Class Mapping กับ Column ไหนในตารางฐานข้อมูล เราทำได้โดยใช้ Annotation `@ORM\Column` ในตัวอย่างข้างต้น เรา Mapping Field `name` กับ Column `name` ในตาราง `products` โดยกำหนด Data Type เป็น `string` และความยาวสูงสุดเป็น 255 ตัวอักษร

**ข้อผิดพลาดที่พบบ่อย:**

  • **ลืมใส่ Annotation `@ORM\Entity`:** ถ้าลืมใส่ Annotation นี้ ORM จะไม่รู้ว่า Class นี้เป็น Entity และจะไม่สามารถจัดการข้อมูลได้
  • **Data Type ไม่ตรงกัน:** ถ้า Data Type ที่กำหนดใน Annotation ไม่ตรงกับ Data Type ของ Column ในฐานข้อมูล อาจจะทำให้เกิด Error ตอน Save ข้อมูล
  • **ชื่อ Column ผิด:** ถ้าชื่อ Column ที่กำหนดใน Annotation ไม่ตรงกับชื่อ Column ในฐานข้อมูล ORM จะไม่สามารถหา Column ที่ถูกต้องได้

Primary Key และ Auto-Increment

Primary Key คือ Column ที่ใช้ระบุแต่ละ Record ในตารางฐานข้อมูลอย่าง Unique โดยปกติแล้ว Primary Key จะเป็น Integer และมี Auto-Increment (ค่าจะถูกสร้างขึ้นโดยอัตโนมัติโดยฐานข้อมูล) ในตัวอย่างข้างต้น เรากำหนดให้ Field `id` เป็น Primary Key และ Auto-Increment โดยใช้ Annotations `@ORM\Id` และ `@ORM\GeneratedValue`

**สำคัญ:** Entity ทุกตัวควรมี Primary Key! ถ้าไม่มี Primary Key ORM จะไม่สามารถระบุ Record ที่ถูกต้องได้

Getters และ Setters

หลังจากที่เราได้สร้าง Entity Class และ Mapping Field กับ Column แล้ว ขั้นตอนต่อไปคือการสร้าง Getters และ Setters สำหรับ Field แต่ละตัว Getters คือ Method ที่ใช้ในการดึงค่าของ Field ส่วน Setters คือ Method ที่ใช้ในการกำหนดค่าของ Field

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;

/**
 * @ORM\Entity
 * @ORM\Table(name="products")
 */
class Product
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="text", nullable=true)
     */
    private $description;

    /**
     * @ORM\Column(type="decimal", precision=10, scale=2)
     */
    private $price;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getDescription(): ?string
    {
        return $this->description;
    }

    public function setDescription(?string $description): self
    {
        $this->description = $description;

        return $this;
    }

    public function getPrice(): ?string
    {
        return $this->price;
    }

    public function setPrice(string $price): self
    {
        $this->price = $price;

        return $this;
    }
}

**คำอธิบาย:**

  • `public function getId(): ?int`: Getter สำหรับ Field `id` (คืนค่าเป็น Integer หรือ `NULL`)
  • `public function setName(string $name): self`: Setter สำหรับ Field `name` (รับค่าเป็น String) และคืนค่าเป็น `$this` (เพื่อให้สามารถ Chain Method ได้)

**ทำไมต้องมี Getters และ Setters?**

ถึงแม้ว่าเราจะสามารถเข้าถึง Field โดยตรงได้ (เช่น `$product->name`) แต่การใช้ Getters และ Setters จะช่วยให้เราควบคุมการเข้าถึงและแก้ไขข้อมูลได้ง่ายขึ้น นอกจากนี้ยังช่วยให้เราสามารถเพิ่ม Logic เพิ่มเติมเข้าไปใน Getter และ Setter ได้ เช่น การ Validate ข้อมูลก่อนที่จะทำการ Save

สรุป

ในบทนี้ เราได้เรียนรู้วิธีการสร้าง Entity Class และ Mapping Field กับ Column ในฐานข้อมูล Entity Class เป็น Object ที่เป็นตัวแทนของตารางในฐานข้อมูล และเราใช้ Annotations หรือ Attributes เพื่อบอกให้ ORM รู้ว่า Class นี้เป็น Entity และ Field แต่ละตัว Mapping กับ Column ไหน การสร้าง Entity อย่างถูกต้องเป็นพื้นฐานที่สำคัญสำหรับการใช้งาน ORM Framework ในการพัฒนาแอปพลิเคชัน

ในบทถัดไป เราจะมาเรียนรู้วิธีการใช้ ORM ในการทำ CRUD Operations (Create, Read, Update, Delete) ซึ่งเป็นพื้นฐานของการจัดการข้อมูลในฐานข้อมูล อย่าลืมติดตามนะครับ!

Office.in.th Custom Service

この構成をもとにシステムを開発・カスタマイズしたいですか?

Office.in.th は、エンタープライズ Web アプリケーション、API 連携、官民の業務管理システムの設計・開発を承り、長期的なサポートも提供します。

ソフトウェア開発サービスを見る