我有这个问题:
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查询构建器而不是原始查询,我该怎么做?
答案 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();