如何解决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问题提示,请问这个该如何解决谢谢
推荐文章: