How would I do this query in laravel

293 views Asked by At

How can I do this in laravel query builder? (this basically gets your current position in a voting system)

SELECT position FROM 
    (SELECT participant.target_user_id, @rownum := @rownum + 1 as position FROM 
        (SELECT target_user_id, count(*) as votes FROM contest_participants_votes GROUP BY 
        target_user_id ORDER BY votes DESC) as participant 
    JOIN (SELECT @rownum := 0) r) x
WHERE target_user_id = 1
1

There are 1 answers

3
user3542112 On BEST ANSWER

We used a raw statement like this with placeholder

$position = \DB::select(\DB::raw(
            'SELECT position FROM 
                (SELECT participant.target_user_id, @rownum := @rownum + 1 as position FROM 
                  (SELECT target_user_id, count(*) as votes FROM contest_participants_votes GROUP BY 
                  target_user_id ORDER BY votes DESC) as participant 
                JOIN (SELECT @rownum := 0) r) x
            WHERE target_user_id = ?'), [$pid]);