duanjiaonie6097
2016-05-08 09:11
浏览 56
已采纳

将原始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?

  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongluzhi5208 2016-05-08 12:25
    已采纳

    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();
    
    打赏 评论

相关推荐 更多相似问题