简体   繁体   English

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

[英]Changing raw SQL query into Laravel Query Builder object

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?我想将其更改为 Laravel 查询构建器而不是原始查询,我该怎么做?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM