访问与Laravel 4的嵌套关系

时间:2013-12-01 20:27:10

标签: php laravel-4 eloquent

我无法弄清楚如何在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_idrole_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

enter image description here

我不知道它是否有所作为但我的id表上没有People字段。 person_id是主键。

1 个答案:

答案 0 :(得分:3)

一旦你访问了演员阵容,这应该很简单......

Route::get('movies', function()
{
    $movie = Movie::find(1);
    $cast  = $movie->cast;

    return View::make('movies')->with(array(
        'movie' => $movie,
         'cast' => $cast));
});
  

注意:此时,$castCollection类的实例,而不是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');
    }
}