简体   繁体   中英

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 :

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.

See https://laravel.com/docs/5.1/eloquent-relationships#has-many-through for extra information.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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