Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

axtg's avatar
Level 5

Complex raw query

Hi!

I can't seem to get this query working in Laravel. The fromRaw() method is not documented anywhere. The code however works fine in my local SQL editor.

What methods am I best off using? Or should I not be wanting to run this at all in Laravel? I am planning to run it daily from a Command to assess rankings.

SELECT 
    c.location_id, ROUND(((@rank - rank) / @rank), 2) AS percentile_rank
FROM
    (SELECT 
    *,
        @prev:=@curr,
        @curr:=CAST(a.value AS unsigned) AS transformed,
        @rank:=IF(@prev = @curr, @rank, @rank + 1) AS rank
    FROM
        (SELECT id, attribute_id, location_id, value FROM attributes_locations) AS a,
        (SELECT @curr:= null, @prev:= null, @rank:= 0 ) AS b
   WHERE a.attribute_id = 4
   AND a.location_id IS NOT NULL
   ORDER BY transformed DESC) AS c
HAVING percentile_rank >= 0.75;
0 likes
3 replies
realrandyallen's avatar
Level 44

Something this complex I'd probably just run through the DB facade, though I can't test if it'd actually work for you:

$sql = <<< EOF
SELECT 
    c.location_id, ROUND(((@rank - rank) / @rank), 2) AS percentile_rank
FROM
    (SELECT 
    *,
        @prev:=@curr,
        @curr:=CAST(a.value AS unsigned) AS transformed,
        @rank:=IF(@prev = @curr, @rank, @rank + 1) AS rank
    FROM
        (SELECT id, attribute_id, location_id, value FROM attributes_locations) AS a,
        (SELECT @curr:= null, @prev:= null, @rank:= 0 ) AS b
   WHERE a.attribute_id = 4
   AND a.location_id IS NOT NULL
   ORDER BY transformed DESC) AS c
HAVING percentile_rank >= 0.75;
EOF;

$results = DB::select($sql);
axtg's avatar
Level 5

I feel like I'm not in the right place running these queries through Laravel, but agreed realrandyallen, this is best done in the rawest way possible.

jlrdw's avatar

Running it through the DB facade and using parameter binding is a normal way it's not raw.

Guess what eloquent at runtime does the exact same thing, all is converted to normal SQL and PDO at runtime.

Please or to participate in this conversation.