vendredi 16 octobre 2015

Laravel nested relationship not working

I have a user model which stores basic user information such as username, password etc.

There are also 3 types of user, Student, Staff and Parent. Each type also has a seperate model. For example, there is a Student model which belongs to a User model.

I also have a relationships table, which stores relationships between students and parents. This relationship is stored in the User model.

If I do something like:

App\Student::first()->user->relations;

It happily returns a collection of related parents.

In my Students model, I have a method called hasParent() which accepts a given user ID, and checks to ensure the student has a parent with that id. In that method, I have the following:

public function hasParent($parent)
{
    return $this->user->relations->where('id', $parent)->count() === 1;
}

However, this returns an error Cannot call 'where' on a non-object. If I debug further, $this->user->relations returns an empty array.

The problem is, like above, if I call the methods separately, I get the results I want.

So to clarify, if I run:

App\Student::first()->user->relations;

This returns a collection of users just fine.

In my Student model however, if I call:

$this->user

Then I get the correct student

If I call

$this->user->relations

I get an empty array. Which doesn't make sense! Can anyone shed any light on this, or what I might be doing wrong? If you need any further info, please let me know.



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire