2013-12-20 34 views
1

我有一張表格,它與已被「喜歡」的藝術家有關係。即像這樣:如何在雄辯查詢生成器(Laravel 4)中使用「SUM」進行排序

artists_id fan_id 
1   1 
1   2 
1   3 
4   1 
4   2 

有表格「藝術家」和「球迷」,包含這些實體的信息。我想通過在Laravel 4中喜歡藝術家在Eloquent查詢構建器中的用戶總數來查詢查詢結果(即按count計數結果,然後按count desc對它們進行排序)。我想拉動藝術家信息。

這是我有:

$artists_most_popular = DB::table('artists') 
         ->join('fanartists', 'artists.id', '=', 'fanartists.artist_id') 
         ->orderBy('sum('fanartists.fan_id')') 
         ->groupBy('artists.id') 
         ->take(50) 
         ->get(); 

     return $artists_most_popular; 

我知道這是不對的,但我在一個損失如何雄辯結構這一點。有任何想法嗎?謝謝。

回答

2

嘗試DB::raworderBy。所以,你的例子是...

$artists_most_popular = DB::table('artists') 
        ->join('fanartists', 'artists.id', '=', 'fanartists.artist_id') 
        ->orderBy(DB::raw('sum(\'fanartists.fan_id\')')) 
        ->groupBy('artists.id') 
        ->take(50) 
        ->get(); 

return $artists_most_popular; 
+0

我得到的錯誤:語法錯誤,意外「fanartists」(T_STRING) – user1072337

+0

這實際上是在你的代碼中的錯誤。我編輯它來解決它。 – Robbo