gpt4 book ai didi

node.js - Sequelize 多重插入数据

转载 作者:行者123 更新时间:2023-12-03 22:36:25 25 4
gpt4 key购买 nike

大家好 =) 这是我第一次在 postgresql 中使用 sequelize,我在使用 sequelize(node.js) 多次插入数据时遇到了问题。我们有一些 table (见图片)

表关系

1) 客户 -> 1:M -> 合约

2) 合约 -> 1:M -> Contracts_attaches

3) 费率 -> 1:M -> Contracts_attaches

Test Tables

客户端模型

const Client = db.define('clients', {
id_clients: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true,
},
nclients: {
type: Sequelize.STRING
}
-some fields-
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
});

速率模型
    const Rate = db.define('rates', {
id_rates: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
}
--fields--
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})

合约模型
    const Contract = db.define('contracts', {
id_contracts: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
--fields--
id_clients: {
type: Sequelize.INTEGER,
allowNull: false
},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
}
})

Contract_attach 模型
const Contract_attach = db.define('contract_attach', {
id: {
type: Sequelize.INTEGER,
allowNull: false,
autoIncrement: true,
primaryKey: true
},
contracts_id: {
type: Sequelize.INTEGER,
references:{
model:'contracts',
key:'id_contracts'
}
},
rate_id: {
type: Sequelize.INTEGER

},
createdAt: {
allowNull: false,
type: Sequelize.DATE
},
updatedAt: {
allowNull: false,
type: Sequelize.DATE
},
})

关联配置
Contract.belongsTo(Contract_attach, { foreignKey:'id_contracts', sourceKey:'contracts_id' });
Contract_attach.hasMany(Contract,{foreignKey:'id_contracts', sourceKey:'contracts_id'});
Contract_attach.hasMany(Rate,{foreignKey: 'id_rates', sourceKey: 'rate_id'});
Rate.belongsTo(Contract_attach, { foreignKey: 'rate_id', sourceKey: 'id_rates' });

插入数据示例

我尝试像这样的代码插入数据
Contract.create({'numcontract':22,'datereg':'2019-12-11','id_clients':5,Contract_attach:[{'rate_id':2,'rate_id':3}]},
{include: [Contract_attach]}).then(result => console.log(result));

或此代码
Contract.create({'numcontract':22,'datereg':'2019-12-11','id_clients':5,Contract_attach:[{'ratename':'Small Buissness','ratename':'Small Buissness 10'}]},
{include: [Contract_attach]}).then(result => console.log(result));

当我尝试使用此代码插入数据时,只为 Contract 表插入数据,而忽略插入 Contract_attach

附注。 Rate 表有数据,我们不需要向 Rate 表插入数据。

最佳答案

对于某些人来说,它可能并且将会有用,但我像这样解决了这个问题

Contr.create({'numcontract':22,'datereg':'2019-12-11','id_clients':5})
.then(function(contr){
contract_att.bulkCreate([{'contracts_id':contr.id_contracts, 'rate_id':2},{'contracts_id':contr.id_contracts,'rate_id':3}]);
});

如果您有其他解决方案,请分享))

关于node.js - Sequelize 多重插入数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59728891/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com