【问题标题】:How can I optimize Laravel Query between two tables?如何优化两个表之间的 Laravel 查询?
【发布时间】: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


【解决方案1】:

你可以使用 Laravel Eloquent 关系。你可以在这里阅读文档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,'type_id','id');}

在您的页面模型中:

use (path to sport model);

public function PSport(){return $this->hasMany(Sport::class,'page_id','id');}

在你看来:

@foreach($data_sport as $val)
echo 'type = '.$val->RType->name;
echo 'pages = '.$val->RPages->name;
@endfoeach

【讨论】:

  • 好吧,我需要运行 foreach($pages as $page) foreach($types as $type)
  • 不是你不知道。它会自动显示您的子表与您的运动表上的一个查询 $foreach 的关系。在你对给定的投票投反对票之前仔细阅读..
猜你喜欢
  • 2019-03-13
  • 2018-03-19
  • 1970-01-01
  • 2021-12-08
  • 2019-07-03
  • 2017-12-14
  • 2018-11-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多