首页 > 解决方案 > 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 上的许多示例所示。

标签: mysqlnode.jsexpresssequelize.js

解决方案


因此,当您使用时,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


推荐阅读