I have a pivot table of category_post
which contains the post_id
and category_id
i also have Post Model
categories(){
return this.belongsToMany('App/Models/Category')
}
Category
posts(){
return this.belongsToMany('App/Models/Post')
}
i am trying to loop all the posts that belongs to a category when user visits this route localhost:3333/category/news
You can use lucids whereHas to get all posts from specific category.
https://adonisjs.com/docs/4.1/relationships#_wherehas
const posts = await Post
.query()
.whereHas('category', (builder) => {
builder.where('slug', 'news')
})
.fetch()
Or if you have already loaded category, you can also eagerLoad posts for it using:
https://adonisjs.com/docs/4.1/relationships#_eager_loading
const category = await Category.query().where('slug', 'news').firstOrFail()
const posts = await category.posts().fetch()
Check docs for.wherePivot also it could be useful to you too: https://adonisjs.com/docs/4.1/relationships#_querying_pivot_table
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.