Polymorphic Relations — Database

Apa itu Polymorphic Relation? Polymorphic relation memungkinkan satu tabel berelasi dengan beberapa tabel lain menggunakan kolom *_type dan *_id. Ini menghindar

Apa itu Polymorphic Relation?

Polymorphic relation memungkinkan satu tabel berelasi dengan beberapa tabel lain menggunakan kolom *_type dan *_id. Ini menghindari duplikasi tabel yang serupa.

Contoh: Comments pada Posts dan Videos

-- Tanpa polymorphic: perlu tabel terpisah
CREATE TABLE post_comments (...);
CREATE TABLE video_comments (...);
-- ❌ Duplikasi struktur!

-- Dengan polymorphic: satu tabel untuk semua
CREATE TABLE comments (
    id SERIAL PRIMARY KEY,
    body TEXT NOT NULL,
    commentable_type VARCHAR(50) NOT NULL, -- "Post" atau "Video"
    commentable_id INT NOT NULL,
    created_at TIMESTAMP DEFAULT NOW()
);

-- Index untuk query cepat
CREATE INDEX idx_comments_commentable
ON comments(commentable_type, commentable_id);

Data di Tabel Comments

| id | body           | commentable_type | commentable_id |
|----|----------------|------------------|----------------|
| 1  | "Bagus!"       | Post             | 5              |
| 2  | "Keren!"       | Video            | 3              |
| 3  | "Setuju!"      | Post             | 5              |

Laravel Polymorphic

// Comment model
public function commentable()
{
    return $this->morphTo();
}

// Post model
public function comments()
{
    return $this->morphMany(Comment::class, 'commentable');
}

// Video model
public function comments()
{
    return $this->morphMany(Comment::class, 'commentable');
}

// Usage
$post->comments;   // semua comment untuk post ini
$video->comments;  // semua comment untuk video ini

Many-to-Many Polymorphic

-- Tags bisa dipakai di Posts, Videos, dan Products
CREATE TABLE taggables (
    tag_id INT REFERENCES tags(id),
    taggable_type VARCHAR(50),
    taggable_id INT
);

Trade-offs

Yang akan kamu pelajari