Laravel 5.1: 只获取相关模型的记录

Laravel 5.1: Get only the records of the related model

我有三个模型:

这些是它们的实现:

class Category extends \Eloquent {
    public function posts() {
        return $this->hasMany('Post');
    }
}


class Post extends \Eloquent {
    public function category() {
        return $this->belongsTo('Category');
    }
    public function comments() {
        return $this->hasMany('Comment');
    }
}

class Comment extends \Eloquent {
    public function post() {
        return $this->belongsTo('Post');
    }
}

是否可以使用 eloquent 获取与类别相关的所有评论(并且只有评论,没有帖子)的列表(数组或集合)? (这意味着,给定一个类别找到所有相关的帖子,然后 return 所有相关的评论)。

提前致谢!

只需在您的模型类别上使用 hasManyThrough 关系:

class Category extends \Eloquent {
    public function posts() {
        return $this->hasMany(Post::class);
    }
    public function comments() {
        return $this->hasManyThrough(Comment:class,Post::class);
    }
}

之后,您只需调用 $category->comments 即可获得包含与类别相关的所有评论的集合。

有关更多信息,请参阅 https://laravel.com/docs/5.1/eloquent-relationships#has-many-through

对于Laravel 5.3:https://laravel.com/docs/5.3/eloquent-relationships#has-many-through