【问题标题】:Sequelize "include" not working white many-to-many relations续集“包含”不起作用的白色多对多关系
【发布时间】:2021-02-13 04:04:27
【问题描述】:

我是 Node 和 Sequelize 的新手,我正在构建一个基本的电子商务。 这些是我的模型

const Product = sequelize.define('product', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  name: {
    type: DataTypes.STRING,
    allowNull: false,
  },
});

const Sale = sequelize.define('sale', {
  id: {
    type: DataTypes.INTEGER,
    autoIncrement: true,
    allowNull: false,
    primaryKey: true,
  },
  isDelivered: {
    type: DataTypes.BOOLEAN,
    defaultValue: false,
    allowNull: false,
  },
});

还有这些关系

Sale.belongsToMany(Product, { through: SaleItem });
Product.belongsToMany(Sale, { through: SaleItem });

当我尝试获取“SaleItems”时问题就开始了

 SaleItem.findAll({
    include: [Product],
  })
  .then(response => {
   console.log(response);
  })

我收到回复:

SequelizeEagerLoadingError:产品未与 saleItem 关联!

这很奇怪,因为我在一对多关系上做同样的事情,而且效果很好。

感谢您的宝贵时间 :)

【问题讨论】:

标签: javascript node.js sequelize.js many-to-many associations


【解决方案1】:

ProductSale 之间存在关联,但它们与 SaleItem 之间没有关联。

您现有的关联只允许执行如下查询:

Sale.findAll({
    include: [Product],
  })
  .then(response => {
   console.log(response);
  })
Product.findAll({
    include: [Sale],
  })
  .then(response => {
   console.log(response);
  })

您需要像这样为SaleItem 添加关联:

SaleItem.belongsTo(Product);
SaleItem.belongsTo(Sale);

为了获取SaleItem 记录以及关联的模型实例。

【讨论】:

    猜你喜欢
    • 2015-05-16
    • 2020-02-08
    • 1970-01-01
    • 2019-11-16
    • 1970-01-01
    • 2021-12-08
    • 1970-01-01
    相关资源
    最近更新 更多