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

I have this query:

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;
    }
}

I would like to change it into a Laravel query builder as opposed to a raw query, how would I do this?

This should work.

$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();