首页 > 解决方案 > 如何在 Adonis Js 中查询数据透视表

问题描述

我有一个数据透视表,category_post其中包含post_id并且category_id 我也有 Post Model

categories(){

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

    }

类别

posts(){

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

    }

当用户访问此路线时,我正在尝试循环属于某个类别的所有帖子localhost:3333/category/news

标签: node.jsadonis.js

解决方案


您可以使用 lucids whereHas 获取特定类别的所有帖子。

https://adonisjs.com/docs/4.1/relationships#_wherehas

const posts = await Post
  .query()
  .whereHas('category', (builder) => {
    builder.where('slug', 'news')
  })
  .fetch()

或者,如果您已经加载了类别,您也可以使用以下方式为它 eagerLoad 帖子:

https://adonisjs.com/docs/4.1/relationships#_eager_loading

const category = await Category.query().where('slug', 'news').firstOrFail()
const posts = await category.posts().fetch()

检查 .wherePivot 的文档,它也可能对您有用: https ://adonisjs.com/docs/4.1/relationships#_querying_pivot_table


推荐阅读