How to Query Pivot Table

I have 3 tables like this

posts table:

ID Subject
1 Jide Goes to school

categories table:

ID Name Slug
1 News news

category_post table

ID category_id post_id
1 1 1

How can i get all the posts for individual categories

my routes is like this Route.get('/category/:slug', 'MainCategoryController.index') i.e localhost:3333/category/news and i want all the posts associated with that category to show.

Post Model

categories(){

      return this.belongsToMany('App/Models/Category')

    }

Category Model

posts(){

      return this.belongsToMany('App/Models/Post')

    }

How can i loop this in my view also.

1 Like

In your controller method, do:

const { slug } = params
const category = await Category.findBy('slug', slug)

const posts = await category.posts().fetch()
2 Likes

Thanks it worked

1 Like