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

chrisan's avatar

Possible to fill related models with a single query?

Say you have models Widget, Lookup1, Lookup2. Lookup1 & Lookup2 are lookup tables where Widget belongsTo Lookup1 and belongsTo Lookup2.

If I just Widget::find(1) and in the template I call $widget->lookup1 and $widget->lookup2 I will end up with 3 queries.

If I try to Widget::find(1)->with(['Lookup1','Lookup2']) I also end up with 3 queries.

If I try ->join('table','first','=','second') they query works correctly but the models aren't populated and again I end up with 3 queries

Is there a way to perform a join of all the lookups and have the models be populated?

0 likes
4 replies
chrisan's avatar

so for the case where there are many lookups, and I don't really need the model most of the time to just display the label value it sounds like the only option is not to use laravel relationships and stick with a join adding a ->select(['widgets.*', 'lookup1.name as lookup1_name', 'lookup2.name as lookup2_name', etc])

which lets me do {{ $widget->lookup1_name }}

chrisan's avatar

I do not have a oneToMany. Also I think when using oneToMany you would be required to use 1 query per each model in the with as you will potentially get many rows and a join would not make sense anyways, so n queries is acceptable.

It's the belongsTo relationship that have n queries for n lookups is what I want to avoid

Please or to participate in this conversation.