简体   繁体   English

Laravel hasManyThrough多态关系

[英]Laravel hasManyThrough polymorphic relation

I have 4 models: User, Photo, Article and Comment.我有 4 个模型:用户、照片、文章和评论。 Comment model is polymorphic and it is used for Photo and Article.评论 model 是多态的,用于图片和文章。

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:在 User.php 我有代码:

/**
* 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.谢谢你的帮助。

@Tim Lewis, thanks. @Tim Lewis,谢谢。 The solution with merge() works. merge() 的解决方案有效。 The filtering with unique() is not necessary in my case, because each Comment can belong to Photo or Article, not both at once.在我的例子中,使用 unique() 进行过滤不是必需的,因为每个评论都可以属于照片或文章,而不是同时属于两者。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM