mysql - Sequelize 包含选项无法获取其他模型

标签 mysql sql node.js sequelize.js sequelize-cli

我有两个属于彼此的模型(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})
}
})
结果为 postman
enter image description here
有人可以帮忙吗?我想要做的是,当我得到 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 集合中,以防将来产品价格更改您过去的订单数据不正确。

关于mysql - Sequelize 包含选项无法获取其他模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66282105/

相关文章:

mysql - 是否可以使用:bind (oracle style) in MYSQL query with Node?

mysql - MySQL 查询中的日期/字符串差异

MYSQL查询: Select 1 rows photo from table for each album

mysql - SQL从每个组中获取最大值

mysql - 如何查询每年的一系列日期?

authentication - Node.js 发送后无法设置 header

node.js - 在 Angular 2 + Electron 中使用绝对路径

java - Unicode 数据不保存到 MySQL 数据库中

php - 类数据库的对象无法转换为字符串

sql - 如何在go lang中测试事务回滚和提交