node.js - 如何使用 Sequelize 创建关联实体?

标签 node.js sequelize.js

我有两个表和第三个关联实体表,例如:
ERD showing Books and Languages, both with one-to-many relationship to BookLanguages
图书:

module.exports = (sequelize, DataTypes) => {
  const Book = sequelize.define(
    "Book",
    {
      title: DataTypes.STRING,
      author: DataTypes.STRING,
    },
    {}
  );
    
  Book.associate = function (models) {

    Book.belongsToMany(models.Language, {
      as: "BookLanguages",
      through: "BookLanguages",
      foreignKey: "bookId",
    });
  };
      
  return Book;
};
语言:
module.exports = (sequelize, DataTypes) => {
  const Language = sequelize.define(
    "Language",
    {
      name: DataTypes.STRING,
    },
    {}
  );

  Language.associate = function (models) {

    Language.hasMany(models.Book, {
      as: "BookLanguages",
      through: "BookLanguages",
      foreignKey: "languageId",
    });
  };
  
  return Language;
};
语言包含以下记录:1. 英语,2. 法语
我想制作一本有英文和法文版本的新书。
图书管理员:
const Sequelize = require("sequelize");
const db = require("../../models/index");
const Book = db.Book;
const Language = db.Language;

exports.createBook = (req, res) => {
  Book.create({
   title: req.body.title,
   author: req.body.author,
   BookLanguages: req.body.languages // an array [1, 2]
 }, {
   include: [ { association: Language, as: "BookLanguages" } ]
  })
    .then((book) => {
      res.json({ status: 200, message: "Book created successfully!" });
    })
    .catch((err) => {
      res.json({ status: 400, message: err });
    });
};
来自 Sequelize 文档的 AFAICT,这应该足够了,但我收到一个错误:TypeError: Cannot read property 'name' of undefined任何人都可以看到我缺少什么,或者我可能对设置这些关联/关联实体有什么误解?

最佳答案

您必须在模型中指定主键才能使 M:N 工作。
{ 类型:DataTypes.STRING,primaryKey:true }
协会
M:N (belongsToMany) 将始终使用主外键只是 PK 的别名,所以没关系。但是,由于您为一个模型设置了别名,那么您必须告诉 sequelize 使用“otherKey”关联到另一个模型的键是什么。

Language.belongsToMany(models.Book, {
  as: "BookLanguages",
  through: "BookLanguages",
  foreignKey: "languageId",
  otherKey : "bookId"
});

Book.belongsToMany(models.Language, {
  as: "BookLanguages",
  through: "BookLanguages",
  foreignKey: "bookId",
  otherKey : "languageId"
});

关于node.js - 如何使用 Sequelize 创建关联实体?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63216558/

相关文章:

node.js - Mongojs - 如何推送到数组?

javascript - 从自定义数据库连接类返回的值是 'undefined' ,使用node.js和ES6

mysql - 使用sequelize根据express.js中的路由连接mysql数据库

javascript - 如何使用 JavaScript 打印 5000 个随机 URL

javascript - 让 Promise 和 Yield 一起工作

node.js - Sequelize 如何在不更改updatedAt的情况下保存?

javascript - 我怎样才能解决 "Cannot read property ' 定义的未定义”?

mysql - 如何创建不可变的 Sequelize 模型属性?

node.js - 错误 : where: "raw query" has been removed, 请使用 where ["raw query", [replacements]]

node.js - 警告 : Task "clean:server" not found