Nested relationship first rows

Posted 2 months ago by DPlachkov

Hello guys, I have an Eloquent problem that i can't seem to solve.

I'm trying to get the first rows only of my nested relationship product.defaultTariffs.matrix

I have 3 models - Product - defaultTariffs - Matrix.

A product can have 2 defaultTariffs.

defaultTariffs can have multiple values in the Matrix table.

Matrix table has lets say a hundred rows for a given tariff_id.

Matrix table has tariff_id, country_id, kilogram, value

What im tryng to do is

$products = Product::with(['defaultTariffs.matrix' => function($query) use ($weight) {
                    ['country_id', $_POST['country_id']],
                    ['kilogram', '>=', $weight],
                ])->orderBy('kilogram', 'asc')->limit(1);

The problem is that if i do that the query is built like this

select * from `tariff_matrix` where `tariff_matrix`.`tariff_id` in (1, 2) and (`country_id` = ? and `kilogram` >= ?) order by `kilogram` asc limit 1

And this returns only a single row for a single. If i remove the


I get all the hundred rows for each defaultTariff

The question is - is there a way for me to eager load only the first row of the nested relationship (the matrix table)

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.