如何解决N+1问题?

控制器

public function show(Comic $comic)
{
    //获取到当前漫画的全部章节列表
    $chapters =$comic->chapters()->get();
    return view('comics.show',compact('comic','chapters'));
}

模型

            public function reads(): MorphMany
            {
                return $this->morphMany(Read::class, 'readable');
            }

    public function checkReads(): bool
    {
        if (auth()->check()) {
            $check = $this->reads()->where('user_id', auth()->user()->id)->first();
            if ($check) return true;
        }
        return false;
    }

模版

 @foreach($chapters as $chapter)
 {{$chapter->name}} - {{$chapter->checkReads() ? '已阅读' : '尚未阅读'}}
 @endforeach

按照这样写法就会出现N+1问题提示,请问这个该如何解决谢谢

《L05 电商实战》
从零开发一个电商项目,功能包括电商后台、商品 & SKU 管理、购物车、订单管理、支付宝支付、微信支付、订单退款流程、优惠券等
《L04 微信小程序从零到发布》
从小程序个人账户申请开始,带你一步步进行开发一个微信小程序,直到提交微信控制台上线发布。
Tomo11111
最佳答案

预加载把关联的 reads 读出来就不会 n+1, 大概代码如下

    public function show(Comic $comic)
    {
        //获取到当前漫画的全部章节列表
        $chapters = $comic->chapters()->with('reads')->get();

        return view('comics.show', compact('comic', 'chapters'));
    }

    public function checkReads(): bool
    {
        if (auth()->check()) {
            return $this->reads
                ->where('user_id', auth()->user()->id)->count();
        }

        return false;
    }
2年前 评论
李小明 (楼主) 2年前
讨论数量: 8
2年前 评论
李小明 (楼主) 2年前
Su (作者) 2年前

with()预加载,再加上分页,不要在模板里面直接遍历模型的时候读取关联数据

2年前 评论
李小明 (楼主) 2年前
Tomo11111

预加载把关联的 reads 读出来就不会 n+1, 大概代码如下

    public function show(Comic $comic)
    {
        //获取到当前漫画的全部章节列表
        $chapters = $comic->chapters()->with('reads')->get();

        return view('comics.show', compact('comic', 'chapters'));
    }

    public function checkReads(): bool
    {
        if (auth()->check()) {
            return $this->reads
                ->where('user_id', auth()->user()->id)->count();
        }

        return false;
    }
2年前 评论
李小明 (楼主) 2年前

$user应当用参数传入

public function checkReads(?User $user = null): bool
{
}
2年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!