情景:在NodeJS中开发RestApi接口,用的是Sequelize连接MySQL,遇到的问题是查询的时候出来的奇葩结果如下:
预期中的结果应该是如下:
[
{
"id": 3,
"title": "标题3",
"content": "内容3",
"createdAt": "2021-03-30T06:39:30.000Z",
"updatedAt": "2021-03-30T06:39:30.000Z",
"tags": [
{
"tagname": "标签1",
"id": 1
},
{
"tagname": "标签2",
"id": 2
}
]
}
]
看这样子是没有将tag作为元素放到blog中去,但是代码换成Sequelize中的示例代码,仍旧是这个鬼样子
下面看代码:
// 创建Blog模型
const Blog = seq.define('blog', {
title: {
type: Sequelize.STRING,
allowNull: false,
},
content: {
type: Sequelize.TEXT,
allowNull: false
}
})
// 创建Tag模型
const Tag = seq.define('tag', {
tagname: {
type: Sequelize.STRING,
allowNull: false,
}
})
//设置关联
Blog.belongsToMany(Tag, { through: "blogtags" })
Tag.belongsToMany(Blog, { through: "blogtags" })
插入:
const tag1 = await Tag.create({
tagname: '标签1'
})
const tag2 = await Tag.create({
tagname: '标签2'
})
// 创建博客
const blog3 = await Blog.create({
title: '标题3',
content: '内容3'
})
blog3.addTags([tag1, tag2])
在数据库中查看的样子:
blog表:
tag表:
blogtags表:
看这样子是没有错的,下面开始查询:
// 多对多查询
const result = await Blog.findAll({
where: {
id: 3
},
include: [{
model: Tag
}],
raw: true
})
console.log('多对多查询结果:', result)
结果就是一开始发的那张截图的样子,唉,到底是哪里有问题呢?
解决办法:
// 多对多查询
const result = await Blog.findOne({
attributes: ['title', 'content'],
where: {
id: 3
},
include: {
model: Tag,
attributes: ['tagname']
}
})
console.log('多对多查询结果:', JSON.stringify(result))
不要加上raw:true
这个设置,加上后就会有问题,然后这样获取出来应该是Sequelize对象,用json.stringify()
处理下就好
另外,这样获取完数据后会默认把联结表的数据也一起查出来,官方文档上说只要在include中设置 attribute:[]
为空就好,类似这样:
但是我这样设置了之后tag数据也出不来了,不知道为什么,暂时没找到解决办法,不过主要的还是上个问题解决了,卡了好久,唉