Bookshelf(knex) - belongsToMany关系不起作用
问题描述:
我一直在尝试使用belongsToMany关系(Bookshelf)在帖子和标签之间建立关系。这里是我的代码:Bookshelf(knex) - belongsToMany关系不起作用
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调试:sql:'select posts
。* from posts
where id
=?限制?'
表
帖子 - ID标题文本created_at的updated_at
标签 - ID名称created_at的updated_at
posts_tags - ID POST_ID TAG_ID created_at的updated_at
代码中是否有任何错误?
答
对不起,这个职位 - 我刚刚错字:
.fetch({widthRelated: ['tags'], require:true})
widthRelated = withRelated !!!!!!