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

时间:2017-03-26 16:31:04

标签: php laravel laravel-5 laravel-5.4

我当前的嵌套for循环:

@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 collection的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 ▶}

1 个答案:

答案 0 :(得分:0)

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

@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