我是使用 Node.js 进行 Sequelize 的新手。我试图将数据插入到我的多对多关系中。根据文档,我们在创建主对象后可以使用 set[modelName] 函数。然而,对我来说情况似乎并非如此。如果有人能指出我正确的方向,我将不胜感激。干杯!
我的学生模型:
const Sequelize = require('sequelize');
const sequelize = require('../db/database');
const Students = sequelize.define('student', {
studentId: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
firstName: {
type: Sequelize.STRING,
allowNull: false
},
middleName: {
type: Sequelize.STRING,
allowNull: true
},
lastName: {
type: Sequelize.STRING,
allowNull: false
},
dateOfBirth: {
type: Sequelize.STRING,
allowNull: false
},
gender: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: true
},
phoneNumber: {
type: Sequelize.STRING,
allowNull: true
}
});
module.exports = Students;
我的联系方式:
const Sequelize = require('sequelize');
const sequelize = require('../db/database');
const Contacts = sequelize.define('contact', {
contactId: {
type: Sequelize.INTEGER,
autoIncrement: true,
allowNull: false,
primaryKey: true
},
firstName: {
type: Sequelize.STRING,
allowNull: false
},
middleName: {
type: Sequelize.STRING,
allowNull: true
},
lastName: {
type: Sequelize.STRING,
allowNull: false
},
dateOfBirth: {
type: Sequelize.STRING,
allowNull: false
},
gender: {
type: Sequelize.STRING,
allowNull: false
},
email: {
type: Sequelize.STRING,
allowNull: true
},
phoneNumber: {
type: Sequelize.STRING,
allowNull: true
}
});
module.exports = Contacts;
我的亲戚:
Student.belongsToMany(Contact, {
through: 'StudentContacts',
timestamps: false
});
Contact.belongsToMany(Student, {
through: 'StudentContacts',
timestamps: false
});
我保存对象的代码
student = new Student({
firstName,
middleName,
lastName,
dateOfBirth,
gender,
email,
phoneNumber,
classId,
tenantId: req.user.tid
});
// create student
const newStudent = await student.save();
newStudent
.setContact({
firstName: contact.firstName,
lastName: contact.lastName,
middleName: contact.middleName,
dateOfBirth: contact.dateOfBirth,
gender: contact.gender,
email: contact.email,
phoneNumber: contact.phoneNumber
})
.save();
console.log('student', newStudent);
更新了代码以反映建议的答案
Student.create(
{
firstName,
middleName,
lastName,
dateOfBirth,
gender,
email,
phoneNumber,
classId,
tenantId: req.user.tid,
contact: [
{
firstName: contact.firstName,
lastName: contact.lastName,
middleName: contact.middleName,
dateOfBirth: contact.dateOfBirth,
gender: contact.gender,
email: contact.email,
phoneNumber: contact.phoneNumber
}
]
},
{
include: [Contact]
}
);
我们来介绍一下将一个产品与多个标签关联起来的能力。设置模型可能如下所示:
class Tag extends Model {}
Tag.init({
name: Sequelize.STRING
}, { sequelize, modelName: 'tag' });
Product.hasMany(Tag);
// Also works for `belongsToMany`.
Now we can create a product with multiple tags in the following way:
代码使用示例
Product.create({
id: 1,
title: 'Chair',
tags: [
{ name: 'Alpha'},
{ name: 'Beta'}
]
}, {
include: [ Tag ]
})
这个例子是关于 hasMany 的,但它对于belongsToMany 来说是一样的
对于多对多关系 - add[modelName] 有效。
例如,如果模型名称为
user
,则方法将为 addUser
。