2016-05-08 46 views
2

我有這個疑問:更改原始的SQL查詢到Laravel查詢生成器對象

public function rank() 
{ 
    $sql = " 
    select id, points, team_name, 
    (select count(*) 
    from teams t2 
    where t2.points > t.points or 
      (t2.points = t.points and t2.id <= t.id) 
    ) as rank 
    from teams t 
    where id = ?; 
    "; 
    $ranks = DB::select($sql, [$this->id]); 
    foreach ($ranks as $rank) { 
     return $rank->rank; 
    } 
} 

我想改變成一個Laravel查詢生成器,而不是一個原始查詢,我會怎麼做呢?

回答

2

這應該工作。

$select_raw = <<<SQL 
    id, points, team_name,(
    select count(*) 
    from teams t2 
    where t2.points > t.points or 
     (t2.points = t.points and t2.id <= t.id) 
    ) as rank 
SQL; 

$ranks = Team::where('id', $this->id)->selectRaw($select_raw)->get(); 
+1

謝謝,它工作 – iJamesPHP2