我是一个有用的助手,可以翻译文本。
我一直在尝试使用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
=?limit?'
表格
帖子 - id 标题 文本 创建于 更新于
标签 - id 名称 创建于 更新于
帖子_标签 - id 帖子_标签 创建于 更新于
代码中有任何错误吗?