Morphs vs Foreign Key

Morphs และ Foreignkey ทั้งสองวิธีที่ใช้สำหรับการสร้างความสัมพันธ์ระหว่าง Table ใน Database แต่มีลักษณะการใช้งานที่แตกต่างกันไป

🆚 Comparison

AspectMorphsForeign Key

Primary Use Case

When multiple models can have the same type of relationship

When the relationship is clear and specific

Table Structure

Single table to store relationships for multiple types

Separate table for each relationship

Columns in the Table

morphable_id, morphable_type

foreign_key_id

Flexibility

High, can easily add new models

Less, requires creating new relationships for each model

Data Integrity Enforcement

Less, no constraints at the database level

High, with foreign key constraints

Common Use Cases

Comments, tags, images

User profiles, orders, order items

Performance

Can be more complex and may require special handling in some cases

High, due to foreign key constraints

Maintenance

Easy to add new models with the same relationship

Easy to maintain clear relationships

Examples in Laravel

Posts, Videos having Comments

User having Profile, Order having Items

Defining Relationships in Models

morphMany, morphTo

hasOne, belongsTo, hasMany, belongsToMany

Creating Relationships in Database

morphs('commentable')

foreign('user_id')->references('id')->on('users')

🅰️ Morphs

การใช้งาน : ใช้ในการสร้างความสัมพันธ์แบบ polymorphic ที่โมเดลหลายตัวสามารถเชื่อมโยงกับโมเดลเดียวกันได้ ใช้สองคอลัมน์: morphable_id และ morphable_type เพื่อระบุ id และชนิดของโมเดล

ข้อดี : มีความยืดหยุ่นสูง เหมาะกับกรณีที่ต้องการเก็บข้อมูล เช่น Posts, Videos, Comments

ข้อเสีย : มีความซับซ้อน ไม่สามารถรักษาความถูกต้องของข้อมูล เนื่องจากไม่มี Foreign Key Constraints และไม่มีประสิทธิภาพในการสืบค้นข้อมูล

🅱️ Foreign Key

การใช้งาน : ใช้ในการสร้างความสัมพันธ์แบบ One-to-One หรือ One-to-Many

ข้อดี : ไม่ซับซ้อน สามารถรักษาความถูกต้องของข้อมูลได้ดีเนื่องจากการอ้างอิงด้วย Foreign Key constraints และมีประสิทธิภาพในการสืบค้นข้อมูล

ข้อเสีย : ขาดความยืดหยุ่น ไม่สามารถใช้กับความสัมพันธ์ที่ต้องการเชื่อมโยงกับหลายตารางพร้อมกันได้

Last updated