Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I manually eager load a model with data in Laravel Eloquent?

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.

like image 308
DisgruntledGoat Avatar asked Oct 18 '25 04:10

DisgruntledGoat


1 Answers

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);
}
like image 92
Davit Zeynalyan Avatar answered Oct 19 '25 20:10

Davit Zeynalyan