提问者:小点点

拉威尔4:哈斯曼尼思。如何使用where访问元素?


我想得到去年一位作者创作的章节。

因此,我有一个作者,书和章节模型。

我通过一个hasMany直通关系进入章节,它在我的作者模型中是这样的:

public function chapters() {
    return $this->hasManyThrough('Chapter', 'Book');
}

一切都很好,因为现在我可以做这样的事情了-

但是我想从去年创作的作者那里得到每一章:

$chapter[$i] = $author->chapters()->where('created_at', '>', Carbon::now()->subdays(365));

问题是,它不是从章节中得到“created_at”,而是从作者那里得到“created_at”。

如果我尝试这样的事情:

$chapters = $author->chapters;

然后尝试:

$chapter = $chapters->where('created_at', '>', Carbon::now()->subdays(365));

我得到的信息是:“不能在非对象上使用位置”或类似的东西。

如果您能帮助我们查阅去年的章节,我们将不胜感激。提前谢谢。

当我在这篇文章中读到的时候,我有一种感觉,如果不雄辩,这是不可能的。我可能在这里是错误的:Laravel/雄辩:hasMany通过的地方

编辑:以下是我的所有型号、控制器和迁移:

http://help.laravel.io/193c1da926554da8448cad1cc3289535acc53574


共2个答案

匿名用户

另一种解决方案是使用约束来加载关系(建议您缓解N 1查询问题)

$author = Author::find(1);

// eager loading
$author->load(array('chapters' => function ($query)
{
    $query->where('chapters.created_at', '>', Carbon::now()->subdays(365))->get();
}));

// Get chapters of an author
$chapters = author->chapters;

匿名用户

试试看

$chapters = $author->chapters();

然后

echo '<pre>';
dd($chapters->where('created_at', '>', Carbon::now()->subdays(365))->get());

指定hasmanythrough关系上的列名

public function chapters()
{
    return $this->hasManyThrough('Chapter', 'Book', 'author_id', 'book_id');
}