node.js - 如何在 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
解决方案
您可以使用 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
推荐阅读
- python - Numba 错误,AttributeError:“数组”对象没有属性“__defaults__”
- bash - Mac命令批处理找不到文件
- html - CSS-单选按钮索引有问题
- javascript - 未定义的反应上下文
- c++ - C ++编译器错误,从单词中删除字母
- angular - 当 ngIf 在父组件上时,离开转换不起作用
- reactjs - 反应显示以下错误,但看起来一切都很好:
- javascript - 如何将字符串数组作为 url 参数传递和读取,以及如何在 javascript 中读取查询参数?
- android - SMS 插件在 ionic 4 和应用程序中不起作用?
- php - fopen(文件/相机胶卷):无法打开流:权限被拒绝 | 拉拉维尔