Laravel hasManyThrough polymorphic relation

79 Views Asked by At

I have 4 models: User, Photo, Article and Comment. Comment model is polymorphic and it is used for Photo and Article.

Structure is:

User
    id
    username
    etc .....

Photo
    id
    filename
    user_id
    etc ......

Article
    id
    user_id
    text
    etc .....

Comment
    id
    text
    user_id //author of the comment( may be the same as author of the photo/article or not)
    commentable_type  //Photo or Article 
    commentable_id
    etc.....


      User
       /\
      /  \
     /    \
    /      \
 Photo    Article
    \      /
     \    /
      \  /
       \/
     Comment

In User.php I have the code:

/**
* Get all user's photo comments
*
*/
public function photoComments()
{
    return $this->hasManyThrough(
        Comment::class,
        Photo::class,
        'user_id',
        'commentable_id',
        'id',
        'id'
     );
}

and

public function articleComments()
{
    return $this->hasManyThrough(
        Comment::class,
        Article::class,
        'user_id',
        'commentable_id',
        'id',
        'id'
     );
}

which return all comments of user's photos and all commens of user's articles. But I want to retrieve all comments of both models at once - Photo and also Article.

I am not unable to find solution. Thanks for your help.

1

There are 1 best solutions below

0
On

@Tim Lewis, thanks. The solution with merge() works. The filtering with unique() is not necessary in my case, because each Comment can belong to Photo or Article, not both at once.