简体   繁体   English

以一对一关系插入数据属于To Sequelize

[英]inserting data in one-to-one relationship belongsTo Sequelize

I have two schema 我有两个模式

  • address 地址
  • employee 雇员

Each employee will have one address so, mine schema is as below 每个员工都有一个地址,所以我的模式如下

employee.js 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;

Below is the Insertation Logic, It doesn't work, how can i perform association insertion 下面是插入逻辑,它不起作用,如何执行关联插入

Item is an object from the array, where i have performed the forEach 项目是数组中的对象,我在其中执行了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));

You will have to add two pieces of code. 您将必须添加两段代码。

In your first snippet, add 在您的第一个代码段中,添加

employee.hasOne(address);

In your second one, change 在第二个,改变

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));

to

Employee.build(obj).save().then((employee) => {
    employee.setAddress(address).then(() => console.log('created')).catch(err => 
    console.log(err));
}).catch(err => console.log(err));

Note: obj.address(address) becomes obj.setAddress(address). 注意:obj.address(address)变为obj.setAddress(address)。

Please let us know if this works! 请让我们知道是否可行!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM