【发布时间】:2021-01-09 00:39:51
【问题描述】:
这是我的逻辑。
Table:
pages:id,name
types:id,name
spots:id,page_id,type_id,name
Model:
Page (hasMany Spot)
Type (hasMany Spot)
Spot (belongsTo Page and Type)
Controller:
$pages = Page::with("spots")->get();
$types = Type::with("spots")->get();
View:
@foreach($pages as $page)
@foreach($types as $type)
{{$page->name}} <br>
{{$type->name}} <br>
{{Spot::wherePageId($page->id)->whereTypeId($type->id)->count()}} // here is n+1 issue
@endforeach
@endforeach
如何优化查询以显示以上视图?
任何建议都将受到高度赞赏。
【问题讨论】:
-
如果您的关系已经定义,那么您不需要获取 Type::lastest() 和 Spot::latest(),只需使用关系即可。
-
我该怎么做?关系已经建立好了。你能给我看一些代码吗?我最关心的是获得点数。如果没有 n+1 问题,我该怎么做?
-
我不明白
pages x types部分...但您可以加载关系计数laravel.com/docs/8.x/… -
pages x types = @foreach(pages as page) @foreach(types as type) @endforeach @enforeach -
但是你需要两个循环?如果您已经定义了 page->type 关系,那么您不需要两个 @foreach 循环。只需直接使用 $page->type->name 访问类型即可。
标签: php mysql laravel eloquent laravel-query-builder