lundi 10 octobre 2016

Accessing relationship of a relationship

I am adding in an announcements feature to my application.

I have an announcements table which stores the announcement and an announcement_active table which stores the undismissed announcements for each user.

When an announcement is created, a record is generated in the announcements table to store this and a record entered in to the announcement_active table for every user for that announcement.

My user model holds a relationship for the active announcements:

public function activeAnnouncements()
    {
        return $this->hasMany('App\ActiveAnnouncements');
    }

I am then accessing this in my view to check for any undismissed announcements like this:

@if (Auth::user()->activeAnnouncements()->count() > 0)
    //code
@endif

The above works fine, it is when I am trying to do a for each loop on the announcements that I am having trouble:

@if (Auth::user()->activeAnnouncements()->count() > 0)
    @foreach(Auth::user()->activeAnnouncements()->announcement as $announcement)
      //code to display announcement
   @endforeach
@endif

It is when I am chaining ->announcement that I run in to trouble. I have defined the relationship like so:

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

However I get the error:

Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$announcement

When using Tinker and running \App\User::find(1)->activeAnnouncements()->first()->announcement the correct announcement shows.

Where am I going wrong when trying to load these in to my foreach loop?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire