Laravel 有很多通过多态关系
我有 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@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.