我希望得到一些作者在去年创建的章节。
因此,我有一个作者,书籍和章节模型。我通过hasManyThrough-Relationship进入章节,它在我的作者模型中看起来像这样:
public function chapters() {
return $this->hasManyThrough('Chapter', 'Book');
}
一切正常,因为现在我可以做这样的事情:$ authors->章节
但是我希望从去年创作的作者那里得到每一章:
$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));
我收到消息:'不能在非对象上使用Where'或类似的东西。
如何访问去年的章节,我们将不胜感激。提前谢谢。
正如我在这篇文章中所读到的那样,我感觉到,这是不可能的,没有不那么好。我可能在这里错了: Laravel / Eloquent : hasManyThrough WHERE
编辑: 以下是我的所有模型,控制器和迁移:
http://help.laravel.io/193c1da926554da8448cad1cc3289535acc53574
答案 0 :(得分: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;
答案 1 :(得分:1)
试
$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');
}