问题描述
这是我的逻辑。
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
任何建议将不胜感激。
解决方法
您可以使用laravel雄辩的关系。您可以在https://laravel.com/docs/7.x/eloquent-relationships
处阅读文档在“运动”表中添加此功能:
use (path to your 'type' model);
use (path to your 'pages' model);
example : use App\Models\Type;
public function RType(){return $this->belongsTo(Type::class,'type_id','id');}
public function RPages(){return $this->belongsTo(Pages::class,'page_id','id');}
在您的类型模型中:
use (path to sport model);
public function TSport(){return $this->hasMany(Sport::class,'id');}
在您的Pages模型中:
use (path to sport model);
public function PSport(){return $this->hasMany(Sport::class,'id');}
并在您看来:
@foreach($data_sport as $val)
echo 'type = '.$val->RType->name;
echo 'pages = '.$val->RPages->name;
@endfoeach
,
如果可能,请在页面和类型之间建立联系。然后,您将使用执行单个查询获取所有数据。