您知道为什么会显示“此集合实例上不存在属性[registrationType]”吗?

时间:2018-07-18 22:48:56

标签: php laravel

您知道为什么“ @if ($nextRegistration->participants->registration_type->contains('certificate_available', 'Y')) [显示“ Property [registrationType] does not exist on this collection instance”吗?

如果“ registration_types”表的“ certificate_available”列的值为“ Y”,我想为每个注册显示一个链接“获取证书”。

<ul class="list-group">
@foreach($nextRegistrations as $nextRegistration)
    @if(!empty($nextRegistration->conference) || !empty($nextRegistration->conference->start_date))
            @if ($nextRegistration->participants->registration_type->contains('certificate_available', 'Y'))                                                 
            <a href="{{route('conferences.certificateInfo',
            [
            'regID'=> $nextRegistration->id])}}"
                   class="btn btn-primary ml-2">Download certificate</a>
            @endif
        </li>
    @endif
@endforeach
</ul>

参与者模型具有registration_type():

class Participant extends Model
{


    public function registration(){
        return $this->belongsTo('App\Registration');
    }


    public function registration_type(){
        return $this->belongsTo('App\RegistrationType');
    }

}

要获取$ nextRegistrations的代码是:

$nextRegistrations = $user->registrations()
            ->with('participants.registration_type')
            ->whereHas(
                'conference',
                function ($query) {
                    $query->where('end_date', '>', now());
                }
            )->paginate($pageLimit);

$ nextRegistrations显示如下:

LengthAwarePaginator {#336 ▼
  #total: 3
  #lastPage: 1
  #items: Collection {#320 ▼
    #items: array:3 [▼
      0 => Registration {#308 ▼
        ...
        #relations: array:1 [▼
          "participants" => Collection {#327 ▼
            #items: array:1 [▼
              0 => Participant {#332 ▼
               ...
                #relations: array:1 [▼
                  "registration_type" => RegistrationType {#337 ▼
                    #fillable: array:7 [▶]
                   ....
                    #attributes: array:10 [▼
                      "id" => 1
                      "name" => "general"
                      "description" => "desc general"
                      "conference_id" => 1
                      "certificate_id" => 1
                      "certificate_available" => "Y"
                    ]
                    ...
                  }
                ]
                ...
              }
            ]
          }
        ]
        ...
      }
      1 => Registration {#321 ▶}
      2 => Registration {#317 ▶}
    ]
  }
  ....
}

1 个答案:

答案 0 :(得分:0)

如何从数据库中检索数据。您可能需要使用with方法:

$data = Participant::with('registration_type')->get()

或在视图中使用“ registration_type”作为方法,而不是属性:

$nextRegistration->participants->registration_type()

您可以在此处找到有关归属关系的更多信息:https://laravel.com/docs/5.6/eloquent-relationships#one-to-many-inverse