2014-12-13 90 views
0

我在SQL這樣複雜查詢:如何通過Laravel Eloquent執行這個複雜的查詢?

Logs::select(DB::raw(
        'COUNT(*) as numberOfPlays' 
       ), 'track_id') 
       ->where('time', '>', $days) 
       ->orderBy('numberOfPlays', 'DESC')->take(100) 
       ->with('track', 'track.album') 
       ->groupBy(\DB::raw("track_id"))->orderBy('numberOfPlays', 'DESC'); 

我如何可以運行上述查詢返回的數據進一步查詢:

SELECT distinct(albumId) as id, 
band,albumName as name, 
SUM(numberOfPlays) as numberOfPlays 
FROM (
SELECT COUNT(*) as numberOfPlays, 
tracks.album_id as albumId, 
a.name as albumName,b.name as band 
FROM logs l 
LEFT JOIN tracks ON tracks.id=l.track_id 
LEFT JOIN albums a ON tracks.album_id = a.id 
LEFT JOIN bands b ON b.id = tracks.band_id 
WHERE l.time>$days 
GROUP by trackid 
ORDER BY numberOfPlays DESC LIMIT 0,100) t 
GROUP BY albumId ORDER BY numberOfPlays DESC"); 

到目前爲止,我已經使用這個成功retreived內查詢?

+0

如果不使用查詢生成器直接查詢它會不會更有益? – MightyPork 2014-12-13 13:39:16

+0

這就是我目前居住的地方。但仍然應該有辦法。 – apsdehal 2014-12-13 14:05:14

回答

1

實際上,您可以通過Eloquent ORM實現類似的結果,並利用返回的收集結果中可用的方法。這是一個例子。考慮到你有所有的模型類。

$logs = Log::with(['track.album', 'track.band'])->where('time', '>', $days)->take(100)get(); 




class Log extends Eloquent { 

    public function track() { 
     return $this->belongsTo('Track'); 
    } 
} 


Class Track extends Eloquent { 

    public function album() { 
    return $this->belongsTo('Album'); 
    } 

    public function band() { 
    return $this->belongsTo('Band'); 
    } 

} 

Class Album extends Eloquent { 

} 


Class Band extends Eloquent {} 

現在,按照自己想要的方式生成結果,您可以使用返回的集合將其項目轉換爲可呈現結構。

首先我們將組按專輯日誌

$logsByAlbum = $logs->groupBy('track.album.id'); 

然後變換分組的日誌

$logsByAlbum->transform(function($album_logs) { 

    if(!empty($album_logs)) { 

     return array(
     'id' => $album_logs[0]->album->id, 
     'album_name' => $album_logs[0]->album->name, 
     'numberOfPlays' => count($album_logs) 
    ); 

    } 

    return array(); 

}); 

After transformation, we need to filter the items with empty values 
$final_result = $logsByAlbum->filter(function($item) { 
     return !empty($item); 
}); 

return $final_result->toArray(); 

這僅僅是一個基本的想法,以幫助您用雄辯的ORM和方法的力量在集合類中提供。

享受! :D