jimmck

Eager Loading

Posted 4 years ago by jimmck

A note before I ask. I don't use Eloquent, simply because I have a library that works well for me. I ported it over from JAVA as a project to learn about PHP's OOP capabilities. That being said I would like to at least understand a package that fills this forum. So I kept seeing post after post about eager loading. Well I was tending to think, well eager loading, oh that must be querying a large record set and returning workable chunks. You know how some one can build meaningful screens and such. So I looked it up in the docs and saw the 'N + 1' problem, hmm. Are we dealing with a physics question here? So I read on. In the example, the documentation is woefully brief on how the API's work, is the example of the problem of books and authors and how Eager Loading will remove duplicate (N + 1) queries. I read this again. So then I read a code snippit.

select * from books

select * from authors where id in (1, 2, 3, 4, 5, ...)

I was astonished? We removed multiple queries of select from Books and then select from Authors. Ok good, but we are coding Join logic that can be done inside the database query, by the SQL engine. Why? Why are we not just Joining Books and Authors by id?

Eager Loading would make sense if I was Joining tables from two totally different, separate databases. But two tables? At a minimum if there is no common id field, any competent database design would refactor it in.

Eloquent's Query Builder even has join commands. So why even introduce the idea of Eager Loading as solution to the 'N + 1' problem?

Am I missing some obvious distinction, perhaps clouded by years of database development in many languages and environments?

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