简体   繁体   English

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

[英]Laravel 5.1: Get only the records of the related model

I have three models: 我有三种模式:

  • Category 类别
  • Post 发布
  • Comment 评论

These are their implementations: 这些是它们的实现:

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');
    }
}

Is it possible, using eloquent, to get a list (array or collection) of all the comments (and only the comments, without posts) related to a Category? 雄辩地,是否有可能获得与类别相关的所有评论的列表(数组或集合)(并且只有评论,没有帖子)? (this means, given a category find all the related posts and then return all the related comments). (这意味着,给定类别,找到所有相关帖子,然后返回所有相关评论)。

Thanks in advance! 提前致谢!

Simply use hasManyThrough relation on your model Category : 只需在模型类别上使用hasManyThrough关系:

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

After that, you can simply call $category->comments to have a Collection with all the comments related to a Category. 之后,您可以简单地调用$category->comments来获得具有与Category相关的所有注释的Collection。

See https://laravel.com/docs/5.1/eloquent-relationships#has-many-through for extra information. 有关其他信息,请参见https://laravel.com/docs/5.1/eloquent-relationships#has-many-through

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM