在Sequelize中为同一模型引用多外键属性时出错

编程入门 行业动态 更新时间:2024-10-10 09:17:50

在Sequelize<a href=https://www.elefans.com/category/jswz/34/1770694.html style=中为同一模型引用多外键属性时出错"/>

在Sequelize中为同一模型引用多外键属性时出错

我使用一个序列化模型,该模型使用两个外键引用同一模型。我在创建父模型时没有问题。但是,当我阅读它们时,出现错误,提示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
            })
        })
回答如下:

尝试一下

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

})

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

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

更多推荐

在Sequelize中为同一模型引用多外键属性时出错

本文发布于:2024-05-07 15:41:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1756969.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:中为   属性   模型   Sequelize   多外键

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!