mysql - sequelize js中查询联表时出现意外输出
问题描述
我正在尝试使用以下代码使用 sequelize 从两个具有一对多关系的表中查询记录。在这种情况下,一位作者可以拥有多本书,而一本书只能由一位作者创作。
const BookList = await Book.findAll({
include: [
{
model: Author,
attributes: ['name'],
},
],
raw: true,
});
图书模型
const Books = sequelize.define(
'books',
{
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING(255),
allowNull: false,
},
author_id: {
type: DataTypes.INTEGER(11),
allowNull: false,
references: {
model: 'authors',
key: 'id',
},
},
},
{
tableName: 'books',
},
);
作者模型
const Authors = sequelize.define(
'authors',
{
id: {
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true,
},
name: {
type: DataTypes.STRING(255),
allowNull: false,
},
},
{
tableName: 'authors',
},
);
预期结果如下。
[
{
id: 1,
name: "book1",
author_id: 1,
author: {
name: "tom",
}
},
.....
]
但是我得到的结果如下。
[
{
id: 1,
name: "book1",
author_id: 1,
"author.name": "tom"
},
.....
]
我的问题是为什么我得到“author.name”而不是作者对象,如 sequelize docs 上的许多示例所示。
解决方案
因此,当您使用时,raw: true
您将收到没有任何格式的原始数据,并且它不绑定到任何模型定义。
如果您希望 sequelize 格式化不同的(使用 dottie.js 在引擎盖下)对象,您可以使用该属性nest: true
const BookList = await Book.findAll({
include: [
{
model: Author,
attributes: ['name'],
},
],
raw: true,
nest: true
});
这里是文档的链接:http: //docs.sequelizejs.com/class/lib/sequelize.js~Sequelize.html
推荐阅读
- c++ - 如何在不解析每一行的情况下将文件流指针移动到特定行(c++)
- google-chrome-devtools - chrome性能css动画中的0fps卡住了
- c# - 使用 BackgroundService 的 .net 核心中的 ServiceBase.RequestAdditionalTime 等效于什么?
- swift - 从多人文本框中获取答案的最佳方法
- java - 使用隔离级别的脏读示例
- javascript - 如何让我的暗模式开关在每次点击时都能正常工作?
- java - 如何使用示例表和输出编写 SQL 查询
- telegram - 如何使用机器人在电报中创建即时视图?
- unix - 在 cygwin 上使用 wget 进行代理身份验证
- hibernate - Jhipster,如何延迟加载实体... Pom 配置,