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

mallaury's avatar

->with() do not join but do another query

Hello,

My Debugbar displayed a lot of duplicated queries. So I tried to investigate. I would like to retrieve all the documents belonging to a user as well as all the authors of these documents (with their avatar). Here is the code :

$documents = $user->documents()->with('user.avatar')->get()

I thought that it would use "INNER JOIN" to select all that elements in 1 query. But it run 3 queries...

select * from `documents` where `is_visible` = ? and `documents`.`id` in (?, ?)
select * from `users` where `users`.`id` in (25)
select * from `avatars` where `avatars`.`id` in (8)

Is it a normal behavior ?

Thanks for your help.

0 likes
5 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Yes that is normal. with() runs a query for each thing it needs to add. If you want joins, you need to write them yourself (but then you dont have relationships)

mallaury's avatar

@Sinnbeck Thanks for your answer. I am pretty sure it is not optimized... Is there a reason why it works like this? And aren't there other solutions to work with "JOIN" without writing them manually?

Thanks

Sinnbeck's avatar

@mallaury If you can come up with a way to create relations using a join, I am sure you can make a PR

Imagine you have 10 users with 50 posts each and 30 comments on each of those.. How would just do a join on that and create a model for each type separately? It would be a huge mess guessing which columns belongs to what

1 like
mallaury's avatar

@Sinnbeck Yes I understand... It is easier to build collections this way. But it wouldn't be impossible

Thanks

Sinnbeck's avatar

@mallaury If someone managed to do it with join, I would imagine that the time it would take alot longer to build it up using php, than it takes to make 3 queries :) But maybe someone smarter than me will prove me wrong some day

Please or to participate in this conversation.