我在Laravel中遇到了一个以前从未遇到过的Eagle Loading问题。
我有以下表格结构
- Letter
id,
sentence_id
- Sentence
id,
paragraph_id
- Paragraph
id,
book_id
- Book
id
belongsTo/belongsToMany:
letter->belongsToMany('Sentence')
sentence->belongsTo('Paragraph')
paragraph->belongsTo('Book')
有/hasMany:
book->hasMany('Paragraph')
paragraph->hasMany('Sentence')
sentence->hasMany('Letter')
这一切都很好。然而,如果我想得到书中所有的字母,我似乎想不出正确的方法。
我试过hasManyThrough
,但很快就意识到这不符合我想要达到的目的。
然后我想我可以用Eager Loading
和hasManyThrough
来达到效果。
public function sentences(){
return $this->hasManyThrough('Sentence', 'Paragraph');
}
然后我可以做一些类似的事情:
Book::sentences()->with(['letters' => function($q) use (&$letters){
$letters = $q->get()->unique();
}]);
然而,这似乎并不能正确地建立这种关系。
通过A
访问D
的最佳方式是什么?
要将letters
关系加载到Book
中,您应该对标准关系执行类似操作:
关系:
Book:
paragraps -> hasMany
Paragraph:
sentences -> hasMany
Sentence:
letters -> hasMany
获取带有字母的书籍
$bookId = 1; // sample book id
$book = Book::with('paragraphs.sentences.letters')->find($bookId);
现在要显示所有可以使用的字母:
foreach ($book->paragraphs as $paragraph) {
foreach ($paragaph->sentences as $sentence) {
foreach ($sentence->letters as $letter) {
echo $letter->id;
}
}
}
我不知道使用这种结构有什么用,但根据使用情况,也许你也应该在数据库中以某种方式复制信息。例如,对于letters
,也许您还应该添加book_id
列,然后您可以使用简单的$book->letters
获得所有书籍的字母,但一切都取决于您如何使用应用程序。