如何优化两个表之间的Laravel查询?

问题描述

这是我的逻辑。

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
,

如果可能,请在页面类型之间建立联系。然后,您将使用执行单个查询获取所有数据。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...