我有两个架构
每位员工都有一个地址,因此我的架构如下
employee.js
const address = conn.define('address', {
street: Sequelize.TEXT,
city: Sequelize.STRING,
postalCode: Sequelize.STRING,
});
const employee = conn.define('employee', {
empId: {
type: Sequelize.INTEGER,
},
name: {
type: Sequelize.STRING,
},
joinDateTime: {
type: Sequelize.DATE,
},
});
address.belongsTo(employee);
employee.sync();
address.sync();
module.exports = employee;
下面是插入逻辑,它不起作用,我如何执行关联插入
Item是数组中的一个对象,我执行了forEach
const obj = {
empId: item.empId,
name: item.name,
joinDateTime: item.joinDateTime,
};
const address = {
street: item.street,
city: item.city,
postalCode: item.postalCode,
};
Employee.build(obj).save().then((resp) => {
/* here how can i perform the insertion in associated address schema
obj.address(address) won't work */
obj.address(address).then(() => console.log('created')).catch(err =>
console.log(err));
}).catch(err => console.log(err));
答案 0 :(得分:0)
您必须添加两段代码。
在您的第一个代码段中,添加
employee.hasOne(address);
在你的第二个中,改变
Employee.build(obj).save().then((resp) => {
/* here how can i perform the insertion in associated address schema
obj.address(address) won't work */
obj.address(address).then(() => console.log('created')).catch(err =>
console.log(err));
}).catch(err => console.log(err));
到
Employee.build(obj).save().then((employee) => {
employee.setAddress(address).then(() => console.log('created')).catch(err =>
console.log(err));
}).catch(err => console.log(err));
注意:obj.address(地址)变为obj.setAddress(地址)。
如果有效,请告诉我们!