node.js - Sequelize 创建belongTo 实例与引用
问题描述
我正在为我的新 NodeJs 项目使用 Sequelize
我用这个关联定义了两个模型:BusinessUnit 和 Store:Store.belongsTo(BusinessUnit);
module.test_data_insertion = function() {
models.BusinessUnit.findOne({
where: {
BUID: "001"
}
}).then(element => {
fs.readdirSync(dir).forEach(function(file) {
var contents = fs.readFileSync(dir + file);
var jsonContent = JSON.parse(contents);
models.Store.create({
StoreId: jsonContent.StoreId,
StoreName: jsonContent.StoreName,
businessUnitId: element.id
});
});
});
};
我找不到正确的方法来引用我的商店中的元素,我想要这样的东西,我不必直接引用 id 字段
module.test_data_insertion = function() {
models.BusinessUnit.findOne({
where: {
BUID: "001"
}
}).then(element => {
fs.readdirSync(dir).forEach(function(file) {
var contents = fs.readFileSync(dir + file);
var jsonContent = JSON.parse(contents);
models.Store.create({
StoreId: jsonContent.StoreId,
StoreName: jsonContent.StoreName,
businessUnit: element
});
});
});
};
它应该很简单,但我看不到。谢谢
解决方案
假设您的关联设置正确,您正在寻找这样的东西:
module.test_data_insertion = function() {
models.BusinessUnit.findOne({
where: {
BUID: "001"
}
}).then(element => {
fs.readdirSync(dir).forEach(function(file) {
var contents = fs.readFileSync(dir + file);
var jsonContent = JSON.parse(contents);
element.setStore({
StoreId: jsonContent.StoreId,
StoreName: jsonContent.StoreName,
});
});
});
};
请从启用方法的文档中阅读belongsTo ,set
但是请注意,如果这是一对多的关系(一个业务部门与许多商店),您可能需要切换到belongsToMany
它的add
方法。因为 setStore 会覆盖之前的设置。
另外,我不确定这些方法中的任何一种是否能在内部.forEach
正常工作,因为它们是有保证的,您可能需要切换到传统的for loop
.
推荐阅读
- flutter - Stateful Widgets 可以保护我设备上的数据吗?
- mysql - 试图获取特定数据的问题数(计数)并使用此信息来验证 Django 模板中的输入字段值
- r - 使用 Graph API 从 R 中的共享点站点读取 excel 文件
- terraform - Terraform:我可以将 ignore_changes 传递给模块吗?
- parsing - 如何在 xtext 中自定义范围生成器以交叉引用文件中的变量
- architecture - DynamoDB 表数据的电子邮件通知架构
- java - 如何在我的 Android 工作室中正确开发暗模式?
- pdf - Yii2:方向不起作用(Kartik 的 ExportMenu)
- python-3.x - 由 joblib 的 Parallel 运行时,Sklearn cv 迭代器参数失败
- php - 多个表到单个 PHP 电子表格