A
A
Alexey Sklyarov2020-01-02 19:50:49
Laravel
Alexey Sklyarov, 2020-01-02 19:50:49

How to display posts from subcategories of this category?

I create a regular table of categories, for which you can assign a parent category in the column parent_idAll posts I add to the lower level category (that is, each post has only one category). When I go to the page of this category (specified to the post), I get a list of posts:

$posts = $category->posts();        
            return view('category.show')->with(compact('category', 'posts'));

In App\Models\Category the posts() method looks like this:
public function posts()
    {
        return $this->hasManyThrough(Post::class, self::class,  'parent_id', 'category_id');
    }

When using this relationship, all posts from child categories are displayed on the page of the parent category, but on the page of any child category, the posts are no longer displayed, in addition, it count()will return zero. If the method is posts() parent_idreplaced by id, then nothing will be displayed in the parent category, but nothing will be displayed in the subcategories. Is it possible to somehow add a link to this relation for the correct display of posts on child categories?

Considered eloquent-has-many-deep , but I think it does about the same thing.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question