Sequelize include选项无法获取其他模型

Sequelize include options cannot get another models

我有两个属于彼此的模型 (order_items.js & products.js) productId 作为 order_items 中的外键,代码如下:

order_items.js

const { DataTypes } = require('sequelize')
const db_config = require(`../config/config`)
const Product = require('./product')

const OrderItem = db_config.define('order_item', {
productId : { type: DataTypes.INTEGER, allowNull:false, references: {model: Product, key: 'id'} },
quantity: { type: DataTypes.INTEGER }
}, {
freezeTableName: true
})


module.exports = OrderItem

product.js

const { DataTypes } = require('sequelize')
const db_config = require(`../config/config`)
const Category = require('./category')

const Product = db_config.define('product', {
productName : { type: DataTypes.STRING, allowNull:false },
productPrice: { type: DataTypes.INTEGER, allowNull:false },
productDescription: { type: DataTypes.STRING, allowNull:true },
productImage: { type: DataTypes.STRING, allowNull:true },
productStock: { type: DataTypes.INTEGER, validate: { min: 0 }, defaultValue: 0, allowNull: false },
CategoryId: { type: DataTypes.INTEGER, allowNull:false, defaultValue: 1, references: {model: Category, key: 'id'}}
}, {
freezeTableName: true

})

module.exports = Product

order_routes.js

router.get('/', async (req, res) => {
try {
  const dataList =  await OrderItem.findAll({include: [{model:Product, required:true}]})
  res.send({
      status: "success",
      message: "data found",
      data: dataList
  }) 
} catch (err) {
    res.send({
        status: "failed",
        message: err})
}
})

邮递员结果

有人可以帮忙吗?我想要做的是,当我得到 order_item 时,它还会得到产品指的是产品的 ID

模型定义中的关联在哪里?我在列字段上看到了参考,但您还需要单独执行以下定义

内部 OrderItem 模型文件

    OrderItem.associate = models => {

        OrderItem.belongsTo(Product, {as: "product", foreignKey: "productId", sourceKey: "id"});

};

内部产品模型文件

    Product.associate = models => {

        Product.hasMany(OrderItem, {as: "orders", foreignKey: "productId", sourceKey: "id"});

};


另外,我建议您也将价格存储在 OrderItem 集合中,以防将来产品价格发生变化时,您过去的订单数据不会不正确。