[英]How can I query in Bookshelf/Knex on a BelongsToMany join table?
[英]Bookshelf(knex) - belongsToMany relation not working
我一直在尝试使用belongsToMany关系(Bookshelf)设置帖子和标签之间的关系。 这是我的代码:
db.js
const Post = bookshelf.Model.extend({
tableName: 'posts',
hasTimestamps: true,
tags: function(){
return this.belongsToMany(Tag)
}
})
const Tag = bookshelf.Model.extend({
tableName: 'tags',
posts: function(){
return this.belongsToMany(Post)
}
})
// Pivot table
const PostTag = bookshelf.Model.extend({
tableName: 'posts_tags',
post: function(){
return this.belongsTo(Post)
},
tag: function(){
return this.belongsTo(Tag)
}
})
获取路线是:
.get('/:id', (req, res, next) => {
db
.Post
.where('id', req.params.id)
.fetch({widthRelated: ['tags'], require:true})
.then((data)=> {
return res.json({data, ralation: data.related('tags').toJSON()})
})
})
我已经在数据库中添加了一个表'posts_tags',并且所有数据库都包含了这个数据透视表。 因此,当我在路由中查询时,关系查询甚至不会启动。 knex debug: sql:'select posts
。* from posts
where id
=? 限制?'
表
帖子 - id标题文本created_at updated_at
tags - id name created_at updated_at
posts_tags - id post_id tag_id created_at updated_at
代码中有错误吗?
对不起这篇文章 - 我只是错字:
.fetch({widthRelated: ['tags'], require:true})
widthRelated = withRelated !!!!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.