Laravel 有很多通过多态关系

发布于 2025-01-17 16:09:36 字数 1162 浏览 3 评论 0原文

我有 4 个模型:用户、照片、文章和评论。评论模型是多态的,用于照片和文章。

结构是:

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

在 User.php 中我有代码:

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

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

返回用户照片的所有评论和用户文章的所有评论。但我想立即检索两个模型的所有评论 - 照片和文章。

我并非无法找到解决方案。感谢您的帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

在你怀里撒娇 2025-01-24 16:09:36

@tim刘易斯,谢谢。使用Merge()的解决方案有效。在我的情况下,使用unique()进行过滤是不需要的,因为每个评论都可以属于照片或文章,而不是同时属于照片或文章。

@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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文