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

ronnyandre's avatar

Not sure how nested eager loading works in this case

I'm working on a quiz like application, where I have three models: Contest, Question and Alternative. A contest has multiple questions, which then again have multiple alternatives.

I can load the contest question data like this: $contest->questions, but I also want to load each of the questions' alternatives, and I tried eager loading: Contest::with('questions.alternatives')->domain('jbv') but this didn't work. (domain() is just a query scope).

The query still looks like this:

select * from `contests` where `domain` = 'jbv'
select * from `questions` where `questions`.`contest_id` = '1' and `questions`.`contest_id` is not null
select * from `alternatives` where `alternatives`.`question_id` = '1' and `alternatives`.`question_id` is not null
select * from `alternatives` where `alternatives`.`question_id` = '2' and `alternatives`.`question_id` is not null
select * from `alternatives` where `alternatives`.`question_id` = '3' and `alternatives`.`question_id` is not null

How can I correctly eager load all alternatives for each question?

0 likes
1 reply
ronnyandre's avatar
ronnyandre
OP
Best Answer
Level 2

Sorry, just figured it out. I tried to edit wrong part of my code.. Stupid mistake :)

Please or to participate in this conversation.