dimanche 22 novembre 2015

Laravel - Relationships, three layers

I'm fairly new to Laravel, and I'm starting to build Relationships. I've got some of the fairly easier stuff down pretty quickly, but I'm struggling with something a tad more advanced.

Essentially, I have three things:

  • Contacts
  • Moments
  • Goals

Under each Contact I can save an Moments, different things I have done with said Contact. Each Moment can also be linked to a Goal.

Now, I'm trying to create a page which will display all of my Goals, under which will appear each of my Moments, and for each Moment I want some basic information as to who the Moment is attached to.

Here is how my tables are setup:

Goals table:

 - id - Goal name - Goal description 

Moments table:

- id - userId - goalId - Moment name - Description

User table

- id - firstname - lastname

So I've got:

class Goal extends Model
{

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

    public function moments() {
        return $this->hasMany('App\Moment', 'goalId');
        }
}

And I've tried the following code to get all the results:

    $goals = Goal::with('moments', 'contact')
        ->where('authId', Auth::id())
        ->where('hidden', 'false')
        ->get();

    dd($goals);

But all contacts return as null... I've tried different things but haven't been able to figure this one out just yet.

Does it use hasManyThrough or something like that?

Thanks for your help !

Cheers, Mark



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire