You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Is it possible to include relations of a polymorphic relationship in the query builder?
Taking this model-structure into account for example:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
/**
* Get the parent commentable model (post or video).
*/
public function commentable()
{
return $this->morphTo();
}
}
class Post extends Model
{
/**
* Get all of the post's comments.
*/
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function contributors()
{
return $this->hasMany(Contributor::class);
}
}
class Video extends Model
{
/**
* Get all of the video's comments.
*/
public function comments()
{
return $this->morphMany(Comment::class, 'commentable');
}
public function reviewers()
{
return $this->hasMany(Reviews::class);
}
}
Now I would like to fetch all Comments with their Commentables, and include the Reviewers (when it's a Video) and the Contributors (when it's a Post).
I don't see how this is possible using the query builder.
An idea that came to mind is to make separate relations for Posts and Videos on the Comments model.
That would work I think, but I don't find it a very strong solution.
Did anyone else face this "problem" and care to share how you solved it?
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
-
Is it possible to include relations of a polymorphic relationship in the query builder?
Taking this model-structure into account for example:
Now I would like to fetch all
Comments
with theirCommentables
, and include theReviewers
(when it's a Video) and theContributors
(when it's a Post).I don't see how this is possible using the query builder.
An idea that came to mind is to make separate relations for
Posts
andVideos
on theComments
model.That would work I think, but I don't find it a very strong solution.
Did anyone else face this "problem" and care to share how you solved it?
Beta Was this translation helpful? Give feedback.
All reactions