Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/262.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel 4急切加载的嵌套关系作为数组返回,我需要模型_Php_Orm_Laravel 4_Eager Loading_Relationships - Fatal编程技术网

Php Laravel 4急切加载的嵌套关系作为数组返回,我需要模型

Php Laravel 4急切加载的嵌套关系作为数组返回,我需要模型,php,orm,laravel-4,eager-loading,relationships,Php,Orm,Laravel 4,Eager Loading,Relationships,访问从嵌套关系检索的对象时遇到问题。我只能以数组的形式访问嵌套关系(它以json的形式返回)。另一个关系作为模型返回。(顺便说一句,我对Laravel 4及其许多概念都是全新的) 假设我使用,$category=category::with('publications.author')->find(5)我可以使用$category->publications对出版物进行迭代,$category->publications[0]->title将返回我期望的结果 我遇到的问题是在尝试访问作者时: $

访问从嵌套关系检索的对象时遇到问题。我只能以数组的形式访问嵌套关系(它以json的形式返回)。另一个关系作为模型返回。(顺便说一句,我对Laravel 4及其许多概念都是全新的)

假设我使用,
$category=category::with('publications.author')->find(5)
我可以使用
$category->publications
对出版物进行迭代,
$category->publications[0]->title
将返回我期望的结果

我遇到的问题是在尝试访问
作者
时:

$category->publications[0]->author->last_name
引发异常-“正在尝试获取非对象的属性”

但是:

$category->publications[0]->author['last\u name']
将返回我想要的内容

这不是一个showstopper,但我希望它能够工作,因为它看起来应该根据Laravel文档工作

那么,我错在哪里呢?我走错方向了吗?我错过什么了吗?我已经检查了我的方法名和定义的关系,并且在我看来都是正确的

这是我的三个模型:“类别”、“出版物”、“作者”。它们之间的关系定义如下:

类别

class Category extends \Eloquent {

protected $table = 'category';

public function publications()
{
    return $this->hasMany('Publication');
}

public function authors()
{
    return $this->hasManyThrough('Publication', 'Author');
}

}
出版

class Publication extends \Eloquent {

protected $table = 'publication';

    public function author()
{
    return $this->belongsTo('Author');
}

    public function category()
{
    return $this->belongsTo('Category');
}
}
作者

class Author extends \Eloquent {

protected $table = 'author';

public function publications()
{
    return $this->hasMany('Publication');
}

}
我想使用以下代码获取我想要的数据:

    $items = array();
    $category = Category::with('publications.author')->find(5);
    foreach($category->publications as $v)
    {
        $items[] = new ContentTeaser($v->title, $v->author->last_name, $v->slug, $v->default_image);
    }

感谢您的关注。

返回许多结果的关系将以
illighted\Database\elounce\Collection
的形式返回,因此您可以将其作为数组进行操作。请参阅动态属性主题下的说明


您提到的模型实际上是PHP中的一个对象。对象没有键,不能作为数组处理,它将具有属性。如果关系是一对多或多对多,则结果集合将从该关系返回多个对象。

我找到了这一个,经过思考,我认为我的问题不是特别清楚。“尝试获取非对象的属性”错误发生在我迭代集合并尝试访问“author”属性(first_name,last_name)时,此时author对象存在一些空结果