kickthemooon
2 years ago
1104
2
Eloquent

All posts from all subcategories

Posted 2 years ago by kickthemooon

this is my category model:

class Category extends Model
{
    ...
    public function parentcategory() {
        return $this->belongsTo('App\Category', 'category_id');
    }

    public function subcategory() {
        return $this->hasMany('App\Category');
    }

    public function articles() {
        return $this->belongsToMany('App\Article');
    }
    ...
}

so I am using this kind of a relationship for the purpose of potential unlimited sub category levels

this is my article model:

class Article extends Model implements HasMediaConversions
{
    ...
    public function categories() {
        return $this->belongsToMany('App\Category');
    }
    ...
}

I am never attaching articles to top level categories (categories that dont have any parent categories).

So I cannot do this $category->articles if the $category is a top level category.

What i need is all the articles from all the sub categories...

I am not sure if taylors recent tweet is related to this:

User::has('posts.comments')->get();

Please sign in or create an account to participate in this conversation.