首页 > 解决方案 > 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
        });
      });
    });
  };

它应该很简单,但我看不到。谢谢

标签: node.jssequelize.js

解决方案


假设您的关联设置正确,您正在寻找这样的东西:

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.


推荐阅读