Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can I use eager loading with complex queries involving joins and subqueries
    Laravel eager loading complex queries joins subqueries database optimization PHP Laravel queries


Can I use eager loading with complex queries involving joins and subqueries


Yes, you can use eager loading with complex queries involving joins and subqueries in Laravel. Here's an example:

php
$posts = Post::with(['comments' => function ($query) {
    $query->select('id', 'post_id', 'body')
          ->whereNotNull('approved_at')
          ->orderBy('created_at', 'desc');
}])
->join('categories', 'posts.category_id', '=', 'categories.id')
->where('categories.name', 'News')
->whereHas('author', function ($query) {
    $query->where('name', 'John Doe');
})
->selectRaw('posts.*, (SELECT COUNT(*) FROM likes WHERE likes.post_id = posts.id) as likes_count')
->orderByDesc('likes_count')
->get();

In this example:

1. We eager load the `comments` relationship, but we also add a constraint to only load approved comments and select specific columns.

2. We join the `posts` table with the `categories` table to only fetch posts from the "News" category.

3. We add a `whereHas` constraint to only fetch posts written by the author "John Doe".

4. We use `selectRaw` to add a subquery to count the number of likes for each post and alias it as `likes_count`.

5. Finally, we order the results by the `likes_count` in descending order.

This demonstrates that you can combine eager loading with complex queries involving joins, subqueries, and constraints to optimize your database queries while still maintaining flexibility in your queries.

Remember to replace the model names, relationship names, and column names with your actual schema.

Citations:
[1] https://www.matthewerwin.co.uk/blog/eager-loading-complex-functions-with-laravel-custom-collections/
[2] https://blog.jgrossi.com/2018/querying-and-eager-loading-complex-relations-in-laravel/
[3] https://laravel-news.com/eloquent-eager-loading
[4] https://dev.to/msnmongare/eager-loading-with-multiple-tables-in-laravel-simplifying-database-queries-4jj7
[5] https://stackoverflow.com/questions/60354755/eager-loading-on-laravel-query-when-nested-3-deep