假设我有三个模型:Chapter、Book、Author。
一本书有许多章节&;属于书本的章节。
作者有很多书&;书籍归属作者。
这意味着ChapterTable有一个book_id,而BookTable有一位author_id。
现在我想数一下所有的章节,来自一个特定的作者。我该如何使用Blade?
以下是我的想法:
$chapters = Book::where('author_id', $author)->with('chapters')->get();
$chapters = lists('chapter_title');
但这些行不能正常工作,因为章节被保存为book_array中的一个数组,我无法像中的"list('chapter_title'(;">
当然,一个解决方案是,给每个章节表一个author_id,然后我就可以做:
$chapters = Chapter::where('author_id', $author)->get();
$chapters = lists('chapter_title');
我知道这会起作用,但如果我的章节表上没有作者id,难道不可能得到以上结果吗?
问候,
George
Eloquent
使用hasManyThrough
:的方式
// Author model
public function chapters()
{
return $this->hasManyThrough('Chapter', 'Book');
}
// then
$author->chapters()->count(); // single query for a single author
为了急于加载多个作者的计数,您需要例如:
// Author model
public function chaptersCount()
{
return $this->chapters()->selectRaw('count(*) as aggregate')->groupBy('author_id');
}
public function getChaptersCountAttribute()
{
if ( ! array_key_exists('chaptersCount', $this->relations)) $this->load('chaptersCount');
return $this->getRelation('chaptersCount')->first()->aggregate;
}
然后:
$authors = Author::with('chaptersCount')->get();
$authors->first()->chaptersCount;
// or for a single author
$author->chaptersCount; // load the relation if needed
您可能想看看这个http://laravel.com/docs/eloquent#querying-关系
$chapters = Book::has('author', $author)->with('chapters')->get();
$chapters = lists('chapter_title');
对于您的章节,您可以访问它们,如Book->chapters