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

lmartins's avatar

Difficulties getting a nested query to work

Hi,

I need to convert a query that is designed to find the higher price from two dimensions matrix (width/height).

On SQL is a fairly trivial query:

SELECT
    price
FROM
    matrices
    INNER JOIN (
            SELECT
                price_group_id,
                max_width
            FROM
                matrices
            WHERE
                price_group_id = 1
                AND max_width >= 74
            ORDER BY
                max_width
            LIMIT 1) AS t ON matrices.max_width = t.max_width
        AND matrices.price_group_id = t.price_group_id
    WHERE
        matrices.max_height >= 84
    ORDER BY
        matrices.max_height
    LIMIT 1

But I'm not being able to convert this into something Laravel can consume.

Thanks so much for any help you may provide.

0 likes
2 replies
lostdreamer_nl's avatar
Level 53
$query = 'SELECT
    price
FROM
    matrices
    INNER JOIN (
            SELECT
                price_group_id,
                max_width
            FROM
                matrices
            WHERE
                price_group_id = 1
                AND max_width >= 74
            ORDER BY
                max_width
            LIMIT 1) AS t ON matrices.max_width = t.max_width
        AND matrices.price_group_id = t.price_group_id
    WHERE
        matrices.max_height >= 84
    ORDER BY
        matrices.max_height
    LIMIT 1';

$result = DB::select(DB::raw($query));

// you can also do this afterwords to get the models
$result = \App\Matrix::hydrate($result );

dd($result );
lmartins's avatar

Oh I was still trying make this work with Laravel's Query Builder methods, but for this use this makes it much simpler.

Thanks so much!

Please or to participate in this conversation.