为什么在 eloquent 中额外查询 运行

Why extra query running in eloquent

以下是我的控制器代码,它首先导致 运行 无用查询

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

query log from laravel dev bar

我想知道为什么在真正的之前额外查询

因为您急于加载用户的兴趣,所以将执行两个查询。一种是检索兴趣,一种是检索用户。

当你不急于加载用户时,像这样:

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

只有 select * from "interests" where "id" in (8, 9, 10) limit 5 会出现在日志中。

除了问题中的两个查询之外,我还希望有一个(第三个)查询 Auth::user()->interests->pluck('id')

您可以在文档中阅读有关 eager loading 和结果查询的更多信息

我认为你可以使用这种方式,不会执行额外的查询

        $interest_ids = Interest::addSelect('id')->whereHas('users', function ($query){
            $query->where('user_id', Auth::id());
        })->get()->pluck('id');

        return User::wherehas('interests', function($query) use($interest_ids){
            $query->whereIn('interest_id', $interest_ids);
        })->take(5)->get();

根据您的 eloquent ,您似乎正在尝试让其他用户有相同的兴趣,我相信这可以按照您的方式完成,但它会加载多个查询,因为 eager loading 而不是仅根据您的情况进行优化,所以我想我的方式是您只能有两个查询,一个用于加载兴趣 ID,一个用于获取其他用户