It seems that eloquent uses a single query for "with" regardless of how many ids there are
Book::with('author')->get();
This would trigger those two queries:
SELECT * FROM books;
SELECT * FROM authors WHERE id IN (...);
The second query may have thousands of author ids in the where clause which might cause problems with performance.
Is there some way so it would chunk that when using with?
I am aware that it is generally not a good idea to query such big result sets.
CodePudding user response:
Yes there are, and its clear in the documentation, you can do something like this:
use App\Models\Flight;
Flight::chunk(200, function ($flights) {
foreach ($flights as $flight) {
//
}
});
Or you can also do this:
use App\Models\Flight;
foreach (Flight::lazy() as $flight) {
//
}
You can get the details in the documentation to learn more: https://laravel.com/docs/9.x/eloquent#chunking-results
CodePudding user response:
if you need only Books and count authors you can use withCount method
Book::withCount('author')->get();