只有first()适用于嵌套关系


Only first() works for nested relationship

我在访问模型集合中的嵌套关系时遇到问题。如果我使用first(),我可以访问该特定模型的关系。例如

public function movie($id)
{
    $member = Movie::find($id)->cast()->first()->person;
    return View::make('movie')->with(array(
        'data' => $member
    ));     
}

在这种情况下,CCD_ 2形成类似于CCD_ 3的结果。这很好,但如果我尝试做这样的事情。。。

$cast = Movie::find($id)->cast;
return View::make('movie')->with(array(
    'data' => $cast
));

在我看来,如果我试着把每个人都打印出来…

foreach ($data->person as $member) {
    echo $member;
}

我得到以下错误:

Undefined property: Illuminate'Database'Eloquent'Collection::$person

我到底做错了什么?我该如何正确地做?

上一个问题

的后续内容

长时间不说话!:)我将一步一步地(为了我自己的理解)进行

首先,在这种情况下,我们采取以下步骤:

$member = Movie::find($id)->cast()->first()->person;
  1. Movie::find($id)->cast()-这里有一个MovieCast对象的集合
  2. ->first()-我们取第一个MovieCast
  3. 。。。->person-我们获取链接到MovieCast对象的Person对象

现在,我们在$member变量中有一个Person对象的实例。也许他有一个名字,或者其他一些属性(created_atmodified_atage,随便什么)。

让我们看看另一种情况:

$cast = Movie::find($id)->cast;

$cast变量中,我们只有MovieCast对象中的Collection。当我们循环到此集合时,我们将返回MovieCast对象的实例。

因此,我们需要像这样循环这些对象(在movie视图中):

// I've used the same $data variable as you're defining in your Controller.
@foreach($data as $d)
    // each $d is a MovieCast object, so you can access his ->person() method.
    <pre>{{ $d->person->name }}</pre>
@endforeach

问题是,通过在foreach中运行echo $data0,您正在针对Collection对象运行它,该对象没有person()方法;因此出现错误!

这有道理吗?