4

For example say I have Book and Author models. I'd eager load the authors like this:

$books = Book::with('author')->get();

But I have already fetched the list of authors with Author::all() in order to display them elsewhere on the page (a select field for filtering). So now Laravel executes 3 queries:

select * from authors;
select * from books;
select * from authors where id in (1, 2, 3, ...);

The third query is obviously superfluous since I already have the authors. Is there some way to pass my $authors Collection into my Book query? Searched through the docs and API and can't find anything.

DisgruntledGoat
  • 70,219
  • 68
  • 205
  • 290
  • Interesting question. I'm not familiar with any way of circumventing the query builder approach to eager loading. You could perhaps do it the other way around: `$authors = Author::with('books')->get();` to get the authors, then `$books = $authors->pluck('books')->unique();` (or similar). Would reduce the queries by one, but using `Collection` logic can still be pretty inefficient. – Tim Lewis Nov 01 '19 at 14:25

1 Answers1

3

You can use this custom code

$authors = Author::get();
$books = Book::get();

foreach ($books as $book) {
    $author = $authors->where('id', $book->author_id)->first();
    $book->setRelation('author', $author);
}
Davit Zeynalyan
  • 8,418
  • 5
  • 30
  • 55