Laravel-无法在第一个关系中循环,但在关系中工作正常



我当前的嵌套循环:

@foreach($auditResults->map->questionDetail as $detail)
    @include('dropdownQuestion', [
        'answer' => $auditResults,
        'detail' => $detail,
        'question' => $detail->auditQuestion
    ])
@endforeach

如您所见,我想将循环中的$auditResults作为answer返回,但此当前设置不起作用。

如果我将 for 循环更改为这个(这在逻辑上是有意义的(:

@foreach($auditResults as $result)
    @foreach($result->map->questionDetail as $detail)
        @include('dropdownQuestion', [
            'answer' => $result,
            'detail' => $detail,
            'question' => $detail->map->auditQuestion
        ])
    @endforeach
@endforeach

我得到Trying to get property of non-object.

如何在不获取非对象属性的情况下循环并返回$auditResults?非常感谢。

$auditResults收藏的DD

Collection {#400 ▼
  #items: array:18 [▼
    0 => Audit {#404 ▼
      #fillable: array:4 [▶]
      #attributes: array:7 [▶]
      #original: array:7 [▶]
      #observables: []
      #relations: array:1 [▼
        "questionDetail" => AuditQuestionDetail {#426 ▶}
      ]
      #touches: []
      +timestamps: true
      #hidden: []
      #visible: []
      #guarded: array:1 [▶]
    }
    1 => Audit {#405 ▶}
    2 => Audit {#406 ▶}
    3 => Audit {#407 ▶}
    4 => Audit {#408 ▶}
    5 => Audit {#409 ▶}
    6 => Audit {#410 ▶}
    7 => Audit {#411 ▶}
    8 => Audit {#412 ▶}
    9 => Audit {#413 ▶}

我假设地图是一对一的关系。在使用之前,您应该检查是否有任何关系数据:

@foreach($auditResults as $result)
  @if ($result->map->count())
    @if ($result->map->questionDetail->count())
      @foreach($result->map->questionDetail as $detail)
          @include('dropdownQuestion', [
              'answer' => $result,
              'detail' => $detail,
              'question' => $detail->map->auditQuestion
          ])
      @endforeach
     @endif
  @endif
@endforeach

最新更新