Polymorphic Relations — Database

A polymorphic relation stores the owner (the data being commented on) in two columns, commentable_type and commentable_id, so one comments table can belong to…

Comments on Sunset Coffee's blog can go on articles, on recipe videos, and later on products too. Can one comments table hold them all, when a foreign key can only point at one table?

It can, with a polymorphic relation: one table can belong to several other tables at once. It only takes two columns: commentable_type (which table the owner is in) and commentable_id (the owner's id). This works like notes pinned on a school noticeboard: each note says "for: Article 5" or "for: Video 3". Handy, one board for everything. But nobody checks that Article 5 still exists. If the article is removed, its notes stay pinned. In the database, the noticeboard is the comments table, each note is one comment row, and the words "for: Article 5" are those two columns. Nobody checks, because commentable_id can't use a foreign key.

The tables we're using

Sunset Coffee now has a blog. There are articles (posts) and recipe videos (videos), and customers can comment on both. Without a polymorphic relation, you'd need two tables with exactly the same columns, post_comments and video_comments, and then a third once products can take comments too.

One comments table for everything

Here are the tables, with one article, one video and three comments:

CREATE TABLE posts (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE videos (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE comments (
  id INTEGER PRIMARY KEY,
  body TEXT NOT NULL,
  commentable_type TEXT NOT NULL,  -- 'Post' or 'Video'
  commentable_id INTEGER NOT NULL  -- the id in that table
);
CREATE INDEX comments_commentable_index ON comments (commentable_type, commentable_id);

INSERT INTO posts VALUES (5, 'The Secret of Palm Sugar Milk Coffee');
INSERT INTO videos VALUES (3, 'How to Make Milk Tea');
INSERT INTO comments VALUES
  (1, 'Nice!', 'Post', 5),
  (2, 'Cool!', 'Video', 3),
  (3, 'Agreed!', 'Post', 5);

The comments table now holds:

id body commentable_type commentable_id
1 Nice! Post 5
2 Cool! Video 3
3 Agreed! Post 5

The query that fetches the comments on article #5:

SELECT * FROM comments WHERE commentable_type = 'Post' AND commentable_id = 5;

The result is rows 1 and 3. Both columns must be in the WHERE. With commentable_id = 5 alone, the query would also fetch comments on Video #5, if there were one. Note the shape: the type name inside single quotes ('Post'), the id a number without quotes. An index on those two columns makes the lookup fast: SEARCH comments USING INDEX comments_commentable_index (commentable_type=? AND commentable_id=?).

Polymorphism in Laravel

In Laravel, the methods for a polymorphic relation use the word morph (from polymorphic):

class Comment extends Model
{
    public function commentable(): MorphTo
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}
// Video is exactly the same: morphMany(Comment::class, 'commentable')

No foreign key to guard it

A foreign key (REFERENCES) always points at one table. commentable_id sometimes points at posts, sometimes at videos, depending on what commentable_type holds. So the database can't put a foreign key on that column, and nothing guards what's in it. Try deleting article #5, then fetching its comments:

DELETE FROM posts WHERE id = 5;
SELECT * FROM comments WHERE commentable_type = 'Post' AND commentable_id = 5;

Guess before you read on: how many rows come back, 0 or 2?

The result is still 2 rows. Those two comments now point at an article that no longer exists. Rows that point at data that no longer exists are called orphans. The database also accepts a comment on an article that never existed:

INSERT INTO comments (body, commentable_type, commentable_id) VALUES ('Hello?', 'Post', 99);
-- accepted, though there's no post #99. Even a typo like 'Psot' is accepted.

So the app has to keep the data consistent. In Laravel, delete the comments yourself when an article is deleted, for example $post->comments()->delete(); before $post->delete();.

The alternative: separate foreign key columns

When there are only a few kinds of owner and new kinds rarely appear, give each kind its own column:

PRAGMA foreign_keys = ON;  -- SQLite only: turn foreign key checks on

CREATE TABLE comments (
  id INTEGER PRIMARY KEY,
  body TEXT NOT NULL,
  post_id INTEGER REFERENCES posts(id) ON DELETE CASCADE,
  video_id INTEGER REFERENCES videos(id) ON DELETE CASCADE,
  CONSTRAINT one_owner CHECK ((post_id IS NOT NULL AND video_id IS NULL)
      OR (post_id IS NULL AND video_id IS NOT NULL))
);
Polymorphic Separate foreign key columns
Adding a new owner Just write a new type A new column and migration
Foreign key Not possible Possible, guarded by the database
Orphan comments Can happen Prevented by the database
Good for Comments, tags, activity logs on many kinds of data A few owners that rarely grow, data that must stay consistent

📌 Many-to-many polymorphic

Tags that can go on articles, videos and products use a polymorphic version of a linking table (Laravel calls it a pivot table):

CREATE TABLE taggables (
  tag_id INTEGER NOT NULL REFERENCES tags(id),
  taggable_type TEXT NOT NULL,
  taggable_id INTEGER NOT NULL
);

tag_id can still have a foreign key, but taggable_id can't, because it points at different tables. In Laravel, the owner's side uses morphToMany(Tag::class, 'taggable'), the tag's side uses morphedByMany(Post::class, 'taggable').

⚠️ Comments that get mixed up, slow, or orphaned

TL;DR: A polymorphic relation stores the owner (the data being commented on) in two columns, commentable_type and commentable_id, so one comments table can belong to posts, videos or products. Fetch with both columns: WHERE commentable_type = 'Post' AND commentable_id = 5. In Laravel, put morphTo() on the comment's side and morphMany(Comment::class, 'commentable') on the owner's side. Its main weakness: it can't use a foreign key, so the database doesn't stop comments on a post that was deleted or never existed. When there are few kinds of owner and the data must stay consistent, use one foreign key column for each kind of owner, such as post_id and video_id.

⚡ Two columns for the owner

Write:

SELECT * FROM comments WHERE commentable_type = 'Post' AND commentable_id = 5;

Meaning: A polymorphic relation stores the owner (the article or video being commented on) in two columns: commentable_type (which table) and commentable_id (which id). So one comments table can relate to posts, videos or products. Always use both columns in the WHERE.

In the exercise, return exactly commentable_type = 'Post' AND commentable_id = 5, with no WHERE in front.

⚡ No foreign key to guard it

Write:

DELETE FROM posts WHERE id = 5;
SELECT * FROM comments WHERE commentable_type = 'Post' AND commentable_id = 5;
Guess first: article #5 has 2 comments. After the article is deleted, how many rows come back, 0 or 2?

Still 2. Those two comments now point at an article that no longer exists, so they're orphans.

Meaning: A foreign key can only point at one table, but commentable_id sometimes points at posts and sometimes at videos. So the database can't guard that column. Your app has to delete the comments.

⚡ When to use separate columns

Meaning: When there are few kinds of owner and the data must stay consistent, use one foreign key column for each kind of owner, such as post_id and video_id. With those columns, the database prevents orphan comments. When there are many kinds of owner, as with comments, tags and activity logs, polymorphic is handier.

What you will learn