skip to Main Content

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.

2

Answers


  1. Yes there are, and its clear in the documentation, you can do something like this:

    use AppModelsFlight;
    
    Flight::chunk(200, function ($flights) {
       foreach ($flights as $flight) {
          //
       }
    });
    

    Or you can also do this:

    use AppModelsFlight;
    
    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

    Login or Signup to reply.
  2. if you need only Books and count authors you can use withCount method

    Book::withCount(‘author’)->get();

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search