我无法弄清楚如何在Laravel中访问嵌套关系。我的具体示例是一个在我的Cast表中有很多内容的电影,在我的People表中有一个条目。这些是我的模特:
MOVIE
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
// Relationships
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');
}
}
PERSON
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}
在我的控制器中,我可以像这样访问演员表(包含person_id
和role_id
):
public function movie($id)
{
$movie = Movie::find($id);
$cast = $movie->cast();
return View::make('movie')->with(array(
'movie' => $movie,
'cast' => $cast
));
}
...但我不知道如何访问name
表格中相应的People
字段。
编辑1:
在@msturdy的答案中使用完全如下定义的类,使用上面的控制器方法,我尝试在我的视图中呈现person
这样的名称:
@foreach($cast->person as $cast_member)
{{$cast_member->person->name}}
@endforeach
这样做我得到错误:
Undefined property: Illuminate\Database\Eloquent\Relations\HasMany::$person
我不知道它是否有所作为但我的id
表上没有People
字段。 person_id
是主键。
答案 0 :(得分:3)
一旦你访问了演员阵容,这应该很简单......
Route::get('movies', function()
{
$movie = Movie::find(1);
$cast = $movie->cast;
return View::make('movies')->with(array(
'movie' => $movie,
'cast' => $cast));
});
注意:此时,
$cast
是Collection
类的实例,而不是MovieCast
类的单个对象,因为 关系定义为hasMany()
您可以在View
(在我的情况下为/app/views/movies.blade.php
@foreach($cast as $cast_member)
<p>{{ $cast_member->person->name }}</p>
@endforeach
用于测试的类定义:
class Movie extends Eloquent {
protected $primaryKey = 'movie_id';
protected $table = 'movie';
public $timestamps = false;
// Relationships
public function cast()
{
return $this->hasMany('MovieCast', 'movie_id');
}
}
class MovieCast extends Eloquent {
protected $table = 'movie_cast';
public $timestamps = false;
public function person()
{
return $this->hasOne('Person', 'person_id');
}
}
class Person extends Eloquent {
protected $primaryKey = 'person_id';
protected $table = 'people';
public $timestamps = false;
public function movieCast()
{
return $this->belongsTo('MovieCast', 'person_id');
}
}