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')
morphTo()goes on the comment's side. It means "belongs to whatevercommentable_typeandcommentable_idsay".$comment->commentablecan return aPostor aVideo.morphMany(Comment::class, 'commentable')goes on the owner's side.'commentable'is the prefix of those two column names. For article #5,$post->commentssends a queryWHERE commentable_type = ... AND commentable_id = 5.- In a migration,
$table->morphs('commentable');makes both columns and their index at the same time. - By default, Laravel fills
commentable_typewith the full class name,App\Models\Post. You can add a morph map (a list of short aliases, one for each model) withRelation::enforceMorphMap(['Post' => Post::class, 'Video' => Video::class]);inAppServiceProvider. After that, it stores the short alias'Post', as in this example. The data stays right even if the class is later moved or renamed.
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))
);
post_idandvideo_ideach have a real foreign key. TheCHECKnamedone_ownermakes sure exactly one column is filled in. A comment on a post and a video at once is refused withCHECK constraint failed: one_owner.DELETE FROM posts WHERE id = 5;now deletes its comments too (ON DELETE CASCADE). A comment on post #99 is refused:FOREIGN KEY constraint failed.- SQLite only checks foreign keys after
PRAGMA foreign_keys = ON;. MySQL (InnoDB) and PostgreSQL always check them. - The downside: a new kind of owner (products, for example) means a new column, a new migration, and an ever longer
CHECK.
| 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
- Filtering on
commentable_idalone. Comments on Post #5 and Video #5 get mixed. Always use both columns. - Forgetting the combined index. Without an index on
(commentable_type, commentable_id), every$post->commentsreads the whole table.morphs()already creates it. - Expecting the database to clean up comments. Deleting a post doesn't delete its comments. Delete them yourself in the app.
- The format in the exercise. Return exactly
commentable_type = 'Post' AND commentable_id = 5: the type in single quotes, the id without quotes, and noWHEREin front.
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.