2017-08-12 53 views
0

我試圖構建一個像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

回答

0

而不是以帖子或評論爲出發點,爲什麼不從報告模型開始?你說你正在建立一個「審覈報告隊列」,這表明查詢報告表(並加入評論/帖子)可能是更自然的解決方案。

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

預先加載加入Laravel公關https://github.com/laravel/framework/pull/13737

+0

我希望有一篇文章/評論只在隊列中列出一次,並列出他們已經報告過多少次。每次報告時,都不會在隊列中列出帖子/評論嗎? – user3325126

+0

是否要按照最近的報告或最近的帖子/評論的順序列出它們?如果通過最近的報告,您仍然可以通過post/comment查詢報告表和組,並獲得每個報告的數量。 – redmallard

+0

最近的評論/文章。感謝您的幫助。 – user3325126