在雄辩的ORM中分组两个查询的结果

问题描述:

我试图构建一个像reddit一样的管理报告队列。在排队我想有文章和评论显示在一起,但我能得到的是一个或另一个具有两个疑问:在雄辩的ORM中分组两个查询的结果

//Get all posts with reports 
Post::whereHas('reports')->with('reports.user')->latest()->get(); 
// Get all comments with reports 
Comment::whereHas('reports')->with('reports.user')->latest()->get(); 

有一个与评论,帖子,并报告多态的关系。表

下面是帖子的输出:

{ 
"id": 7, 
"author_id": 1, 
"title": "A forum post!", 
"body": "<p>Some Forum post content</p>", 
"created_at": "2017-08-08 23:03:22", 
"updated_at": "2017-08-08 23:03:22", 
"reports": [ 
    { 
     "id": 5, 
     "user_id": 1, 
     "content": "Rule 1", 
     "reportable_id": 7, 
     "reportable_type": "App\\Post", 
     "created_at": "2017-08-11 19:32:02", 
     "updated_at": "2017-08-11 19:32:02", 
     "user": { 
     "id": 1, 
     "role_id": 1, 
     "name": "Admin", 
     "created_at": "2017-08-01 18:37:18", 
     "updated_at": "2017-08-10 18:59:52" 
     } 
     } 
    ] 
}, 

我将如何查询这两个职位和评论?

编辑 我不想急于加载与帖子的评论。我想加入上面列出的两个查询。我觉得在阅读后我需要在两个查询之间创建一个union,因为我不认为我可以将它们结合在一起。我只是不知道该怎么做。

+0

尝试这条道路'后> comment->报告 - > user'?我不是说这是一个代码,而是遵循这条路径?是帖子和评论相关吗? –

+0

你可以一次加载多个关系,尝试'Post :: whereHas('reports') - > with('reports.user','comment') - > latest() - > get();' –

+0

得到一篇文章的评论,而不是只有报道的评论不是吗?我基本上是想这两个查询组合在一起,然后组织了最新: '邮政:: whereHas( '报告') - >与( 'reports.user')'' 评论:: whereHas( '报告') - > with('reports.user')' 热门评论将获得与帖子相关的所有评论,而不是评论。我认为。 – user3325126

而不是以帖子或评论为出发点,为什么不从报告模型开始?你说你正在建立一个“审核报告队列”,这表明查询报告表(并加入评论/帖子)可能是更自然的解决方案。

Reports::latest()->with('reportable', 'user')->get() 

预先加载加入Laravel公关https://github.com/laravel/framework/pull/13737

+0

我希望有一篇文章/评论只在队列中列出一次,并列出他们已经报告过多少次。每次报告时,都不会在队列中列出帖子/评论吗? – user3325126

+0

是否要按照最近的报告或最近的帖子/评论的顺序列出它们?如果通过最近的报告,您仍然可以通过post/comment查询报告表和组,并获得每个报告的数量。 – redmallard

+0

最近的评论/文章。感谢您的帮助。 – user3325126