yougotnet's avatar

Why doesn't Laravel use joins when pulling belongsTo or hasOne

If I have a Model B that belongsTo Model A and I ask for Model A with Model B it would be more efficient to pull Model A with a join Model B.

I am using DebugBar and seeing that it issues 2 sql statements; one to retrieve Model A and one to retrieve Model B.

It is more efficient to pull Model A with a join of Model B so there is only 1 hit on the DB instead of 2.

0 likes
4 replies
jlrdw's avatar

You're overthinking this there are two styles of doing this one is as you suggest the other is like a monthly report.

For example company A with their receivables Company B and their receivables Etc.

Join is used a lot with a group by for a different style of report.

The two query technique is more like an invoice with the order details. In other words a Master detail or parent-child relationship.

So it depends on what data you need and how you need it.

See my answer here

https://laracasts.com/discuss/channels/code-review/guidance

yougotnet's avatar

I see your point, but if you have thousands of users on an application; it is more efficient for a one query solution or a two query solution?

jlrdw's avatar

The one extra query to get parent (master) is no big deal even if millions of users.

A join has to transverse over two tables.

You might want to take a basic sql tutorial. Or study the various selects, joins, etc here.

https://dev.mysql.com/doc/refman/8.0/en/

Again it depends on what data you need and how needed.

Snapey's avatar

consider model A has 10 columns of data, and you are interested in 1 model

consider model B has 10 columns and there are 100 rows belonging to column A

with two queries, in memory you have two simple queries and one instance of A and 100 instances of B

with a join, you have 100 records in memory but all the columns of model A are duplicated over and over

so, separate queries might seem more inefficient but they are simpler and quicker than joining tables, and can be far more memory efficient

Please or to participate in this conversation.