繁体   English   中英

访问与Laravel 4的嵌套关系

[英]Accessing nested relationship with Laravel 4

我无法弄清楚如何在Laravel中访问嵌套关系。 我的具体示例是一个在我的Cast表中有很多内容的电影,在我的People表中有一个条目。 这些是我的模特:

电影

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');
    }
}

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
        ));
    }

...但我不知道如何访问我的People表中的相应name字段。

编辑1:

使用类完全按照以下@ msturdy的回答定义,与控制器上面的方法我尝试呈现person的名字,像这样我的观点里:

@foreach($cast->person as $cast_member)
        {{$cast_member->person->name}}
    @endforeach

这样做我得到错误:

Undefined property: Illuminate\\Database\\Eloquent\\Relations\\HasMany::$person

在此输入图像描述

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

它应该很简单,一旦你访问了演员......

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');
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM