I find it difficult to understand how to access nested relationships in Laravel. The specific example that I have is a movie that has many features in my Cast table, which has one entry in my People table. These are my models:
Movie
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
public function cast()
{
return $this->hasMany('MovieCast', 'movie_id');
}
}
MOVIECAST
class MovieCast extends Eloquent {
protected $table = 'movie_cast';
public function person()
{
return $this->hasOne('Person', 'person_id');
}
public function netflix()
{
return $this->belongsTo('Movie', 'movie_id');
}
}
FACE
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}
In my controller, I can access the listing (containing person_id
and role_id
) as follows:
public function movie($id)
{
$movie = Movie::find($id);
$cast = $movie->cast();
return View::make('movie')->with(array(
'movie' => $movie,
'cast' => $cast
));
}
... but I do not know how to access the corresponding field name
in my table People
.
EDIT 1:
Using classes, as indicated in @msturdy's answer below, using the controller method above, I am trying to display names person
like this inside my view:
@foreach($cast->person as $cast_member)
{{$cast_member->person->name}}
@endforeach
When doing this, I get an error message:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$person

, , id
People
. person_id
- .