【问题标题】:Error in referencing multi foreign-key attribute for same model in Sequelize在 Sequelize 中为同一模型引用多个外键属性时出错
【发布时间】:2020-09-01 04:46:36
【问题描述】:

我使用了一个使用两个外键引用同一模型的续集模型。我在创建父模型时没有问题。但是当我阅读它们时,它会给出错误提示 Cannot read property 'name' of undefined.

这是我的模型定义以及我如何选择它。

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Product = sequelize.define('Product', {
    //common fields
  }, {});
  Product.associate = function(models) {
    // associations can be defined here
    Product.belongsTo(models.Unit, {
      as: 'stockUnit',
      foreignKey: 'stockUnitFk'
    })
    Product.belongsTo(models.Unit, {
      as: 'retailUnit',
      foreignKey: 'retailUnitFk'
    })
  };
  return Product;
};

--

'use strict';
module.exports = (sequelize, DataTypes) => {
  const Unit = sequelize.define('Unit', {
    name: {type: DataTypes.STRING, unique: true},
  }, {});
  Unit.associate = function(models) {
    // associations can be defined here
  };
  return Unit;
};

--

Product.findAll({inculde: [Unit]}).then(products => {
            products.forEach(element => {
            console.log(element.stockUnit.name) //this gives an error
            })
        })

【问题讨论】:

    标签: node.js sequelize.js


    【解决方案1】:

    试试这个

    Product.findAll({ include: [{ model: Unit, as: 'stockUnit' }] }).then(products => {
    
    })
    

    如果关联有别名(使用as 选项),则必须指定 包含模型时的此别名。而不是传递模型 直接到include 选项,您应该提供一个对象 有两个选项:modelas

    https://sequelize.org/master/manual/eager-loading.html#fetching-an-aliased-association

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 1970-01-01
      • 2020-10-06
      • 1970-01-01
      • 1970-01-01
      • 2020-07-16
      相关资源
      最近更新 更多