我试图使用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时,您将收到没有任何format的brut数据,并且它不会绑定到任何模型定义。

如果你想要与format续集不同(使用引擎盖下的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