'Why extra query running in eloquent

Following is my controller code which is cause running useless query first then

        $users = Interest::with('users')->
        whereIn('id',Auth::user()->interests->pluck('id'))
        ->take(5)->get();

query log from laravel dev bar

I wonder why extra query before real one



Solution 1:[1]

Because you are eager loading the users with the interests, two queries will be executed. One to retrieve the interests, and one to retrieve the users.

When you would't be eager loading the users, like this:

Interest::whereIn('id', Auth::user()->interests->pluck('id'))
    ->take(5)
    ->get();

only select * from "interests" where "id" in (8, 9, 10) limit 5 would be in the logs.

Next to the two queries in the question, I would also expect a (third) query for Auth::user()->interests->pluck('id').

You can read more in the docs about eager loading and the resulting queries

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 piscator