【问题标题】:Laravel query with relationship has many duplicated query具有关系的 Laravel 查询有很多重复的查询
【发布时间】:2023-02-13 16:20:00
【问题描述】:

表A

  • 编号
  • 全名
  • 分支名称

表B

  • 编号
  • 分支代码
  • 分支名称

我想显示列表表 A 及其分支名称

这是表A中的关系

public function Branch () {
        return $this->belongsTo('App\Model\Branch','branch_code','branch_code');   
    }

这是控制器

 $TableA= TableA::orderBy('created_at','ASC')->get();

这是我的刀片

@foreach($TableAas $data)
<tr>
    <td>{{ $i }}</td>
    <td>{{$data->fullname}}</td>
    <td>{{$data->Branch->branch_name}}</td>
</tr>
  @endforeach

实际上它有效。但是当我调试时,我看到了很多这样的重复查询

select top 1 * from [users] where [users].[branch_code] = '1001'

从 [users] 中选择前 1 *,其中 [users].[branch_code] = '1002' 39.46 毫秒 查看::索引:267

有没有办法让查询更简单快捷? 感谢你

【问题讨论】:

    标签: laravel foreach duplicates


    【解决方案1】:

    使用 with 加载关系

     $TableA= TableA::with('Branch')->orderBy('created_at','ASC')->get();
    
    

    检查EagerLoading问题和N+1问题

    【讨论】:

      猜你喜欢
      • 2017-06-15
      • 1970-01-01
      • 2021-09-14
      • 2020-05-02
      • 2018-07-24
      • 2018-03-01
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多