กลับไปหน้าหลัก

บทที่ 4: Relations และ Associations

เรียนรู้การสร้างความสัมพันธ์ระหว่างตารางใน Prisma Schema! 🔗
40 นาที
ระดับปานกลาง
Database Design

🔗 ประเภทของ Relations

One-to-One
ง่าย

หนึ่งผู้ใช้มีหนึ่งโปรไฟล์

ตัวอย่าง:
User ↔ Profile
One-to-Many
ง่าย

หนึ่งผู้ใช้มีหลายโพสต์

ตัวอย่าง:
User → Posts
Many-to-Many
ปานกลาง

หลายผู้ใช้มีหลาย roles

ตัวอย่าง:
Users ↔ Roles
Self Relations
ขั้นสูง

ผู้ใช้มีหัวหน้าเป็นผู้ใช้คนอื่น

ตัวอย่าง:
User → Manager (User)

📖 ตัวอย่าง Relations แบบละเอียด

One-to-One Relations

ความสัมพันธ์แบบหนึ่งต่อหนึ่ง ใช้สำหรับข้อมูลที่มีความเชื่อมโยงกันแบบเฉพาะเจาะจง

model User {
  id      Int     @id @default(autoincrement())
  email   String  @unique
  name    String?
  profile Profile?
}

model Profile {
  id     Int    @id @default(autoincrement())
  bio    String?
  avatar String?
  userId Int    @unique
  user   User   @relation(fields: [userId], references: [id])
}

💡 Best Practices สำหรับ Relations

✅ สิ่งที่ควรทำ
  • ใช้ชื่อ field ที่สื่อความหมาย เช่น authorId แทน userId
  • เพิ่ม @unique ใน foreign key สำหรับ one-to-one relations
  • ใช้ onDelete: Cascade สำหรับ dependent records
  • ออกแบบ indexes สำหรับ foreign keys ที่ค้นหาบ่อย
❌ สิ่งที่ไม่ควรทำ
  • สร้าง circular dependencies ระหว่าง models
  • ใช้ many-to-many เมื่อ one-to-many เพียงพอ
  • ลืมตั้งค่า referential actions อย่างเหมาะสม
  • ค้นหาข้อมูล relations ลึกเกินไปใน production

📖 Quick Reference

Relation TypeSchema PatternUse CaseExample
One-to-Oneforeign key + @uniqueข้อมูลเสริมที่ไม่บังคับUser ↔ Profile
One-to-Manyforeign keyความเป็นเจ้าของUser → Posts
Many-to-Manyjunction tableการจัดหมวดหมู่Users ↔ Roles
Self Relationforeign key → same tableโครงสร้างลำดับชั้นUser → Manager