【发布时间】:2016-01-12 21:56:42
【问题描述】:
我遇到了一个以前在 Laravel 中使用 Eager 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 的最佳方式是什么?
【问题讨论】:
标签: php laravel laravel-4 eloquent eager-loading