2

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?

1 Answer 1

2

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();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.