In Laravel, Eloquent relationships provide a convenient way to interact with related database tables. Both polymorphic relationships and standard (non-polymorphic) relationships fall under the umbrella of Eloquent relationships, but they serve different purposes.
Standard (Non-Polymorphic) Relationships:
- In standard relationships, you have a straightforward connection between two models using foreign key constraints.
- For example, you might have a
Post
model and aComment
model, where each comment belongs to a post. In this case, you would have aposts
table and acomments
table. Thecomments
table would have a foreign key column likepost_id
that references theid
column in theposts
table. - You define the relationship in the models, and Eloquent provides methods to query and retrieve related data.
Post Model:
// Post Model
class Post extends Model
{
public function comments()
{
return $this->hasMany(Comment::class);
}
}
Comment Model:
// Comment Model
class Comment extends Model
{
public function post()
{
return $this->belongsTo(Post::class);
}
}
Usage:
// Get comments for a post
$comments = Post::find(1)->comments;
Polymorphic Relationships:
- Polymorphic relationships allow a model to belong to more than one type of other model on a single association.
- This is useful when you have entities that can be associated with multiple types of other entities without having to create a separate table for each relationship.
- In a polymorphic relationship, the related model’s type and ID are stored in columns on the calling model’s table.
- For example, you might have a
Comment
model that can belong to bothPost
andVideo
models. In this case, you would have acomments
table withcommentable_type
andcommentable_id
columns.
Comment Model:
// Comment Model
class Comment extends Model
{
public function commentable()
{
return $this->morphTo();
}
}
Post Model:
// Post Model
class Post extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
Video Model:
// Video Model
class Video extends Model
{
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
}
Usage:
// Get comments for a post
$comments = Post::find(1)->comments;
// Get comments for a video
$comments = Video::find(1)->comments;
In summary, standard relationships are used when there’s a direct one-to-many or many-to-one connection between models, while polymorphic relationships are used when a model can belong to multiple types of other models on a single association.