[英]Bookshelf(knex) - belongsToMany relation not working
I have been trying to setup a relation between Posts and Tags using belongsToMany relation (Bookshelf). 我一直在尝试使用belongsToMany关系(Bookshelf)设置帖子和标签之间的关系。 Here is my code: 这是我的代码:
db.js 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 route is: 获取路线是:
.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()})
})
})
I have already added a table 'posts_tags' in database and all the database is seeded including this pivot table. 我已经在数据库中添加了一个表'posts_tags',并且所有数据库都包含了这个数据透视表。 So when I query in route, the relationship query does not even initiate. 因此,当我在路由中查询时,关系查询甚至不会启动。 knex debug: sql: 'select posts
.* from posts
where id
= ? knex debug: sql:'select posts
。* from posts
where id
=? limit ?' 限制?'
Tables 表
posts - id title text created_at updated_at 帖子 - id标题文本created_at updated_at
tags - id name created_at updated_at tags - id name created_at updated_at
posts_tags - id post_id tag_id created_at updated_at posts_tags - id post_id tag_id created_at updated_at
Is there any mistake(s) in code? 代码中有错误吗?
Sorry for this Post - I had just the typo: 对不起这篇文章 - 我只是错字:
.fetch({widthRelated: ['tags'], require:true})
widthRelated = withRelated!!!!!! widthRelated = withRelated !!!!!!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.