我想获得作者在去年创建的章节。
因此我有一个作者,书和章节模型。
我通过一个hasManyThrough-Relationship来访问章节,它在我的Author-Model中看起来像这样:
public function chapters() {
return $this->hasManyThrough('Chapter', 'Book');
}
一切正常,因为现在我可以做这样的事情:$authors->chapter
但我想从作者那里得到每一章,在过去的一年里创作的:
$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));
我得到这样的信息:'Can't use Where on a non-object'或类似的东西。
关于如何访问去年的章节,任何帮助都将不胜感激。提前谢谢。
当我读到这篇文章时,我有一种感觉,如果没有雄辩,这是不可能的。我可能错了:Laravel/Eloquent: hasManyThrough WHERE
编辑:这是我所有的模型,控制器和迁移:
http://help.laravel.io/193c1da926554da8448cad1cc3289535acc53574另一种解决方案是用约束预先加载关系(建议这样做,因为可以缓解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;
try
$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');
}