将原始SQL查询更改为Laravel Query Builder对象

时间:2016-05-08 09:11:01

标签: php mysql sql database 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查询构建器而不是原始查询,我该怎么做?

1 个答案:

答案 0 :(得分: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();