2017-03-08 128 views
0

我真的很迷惑,在雄辯的是,用於選擇流行的線程時流行的參數是選擇表的線程次序存在的差異表,所以我的表看起來像波紋管:我怎麼能由流行線程laravel

------------------- 
| thread  | 
------------------- 
|id (int)   | 
|title (varchar) | 
|value (text)  | 
|timestamp   | 
------------------- 

------------------- 
| comment  | 
------------------- 
|id (int)   | 
|value (text)  | 
|id_thread (id) | 
|timestamp   | 
------------------- 

所以與上表,我想顯示所有線程使用雄辯laravel大多數評論線程。 我花了很多時間在這種情況下,但沒有得到解決。

回答

1

嘗試

$tops = Thread::join('comments', 'comments.id_thread', '=', 'threads.id') 
->select(
    'thread.*', 
    DB::raw('count(comments.id) as total_comments') 
)->orderBy('total_comments', 'desc') 
->groupBy('threads.id') // or 'id' 
->take(10) //top 10 ? 
->get(); 

您可能會遇到到GROUPBY說這樣的東西「......因爲它沒有包含在grouby」相關的錯誤。這意味着你必須對該欄進行分組。顯示該錯誤的每一列都將其添加到組中。

+0

它仍然顯示錯誤, '語法錯誤或訪問衝突:1055'thread.id'不在GROUP BY中。 很多查詢,我嘗試,總是顯示這樣。 Iam卡在這裏 –

+0

你沒注意我旁邊的評論。我爲你更新了代碼。我警告你可能會看到這些錯誤。只需將列添加到groupBy中,以逗號分隔'groupBy('column1','column2')' – EddyTheDove

+0

哦,我很抱歉沒有注意到警告。終於解決了,非常感謝你先生。 –