sequelize 添加方法多对多不起作用

问题描述 投票:0回答:1

我有

Order.belongsToMany(Product, { through: 'OrderProducts'});
Product.belongsToMany(Order, { through: 'OrderProducts' });

我想将产品添加到我当前的订单中

let newOrder = null
        
        const myuser = await User.findByPk('4455a5b1-08bf-4565-9a82-862cc5fdbd3c')
       


        const currentOrder = await Order.findOrCreate({ where : { UserId : '4455a5b1-08bf-4565-9a82-862cc5fdbd3c',onay : false, } })
       
        const productId = '5ba82614-7856-43ee-8262-0859081786ae'
        const adet = 5
        let foundProduct = await Product.findByPk(productId)

        let a = await currentOrder.addOrderProducts(foundProduct)

当我这样做时,我收到以下错误

我尝试了几种方法 set get 与它不起作用

TypeError: currentOrder.addOrderProducts is not a function
sequelize.js
1个回答
0
投票

出现错误“TypeError: currentOrder.addOrderProducts is not a function”是因为 addOrderProducts 方法不能直接在 currentOrder 实例上使用。相反,它应该在订单和产品之间的关联上可用。要解决这个问题,您可以修改代码如下:

// Assuming you have the necessary imports and associations set up

// Find or create the order
const [currentOrder, created] = await Order.findOrCreate({
  where: { UserId: '4455a5b1-08bf-4565-9a82-862cc5fdbd3c', onay: false },
});

// Find the product
const product = await Product.findByPk('5ba82614-7856-43ee-8262-0859081786ae');

// Add the product to the order
if (product) {
  await currentOrder.addProduct(product, { through: { adet: 5 } });
} else {
  // Handle the case where the product is not found
}
© www.soinside.com 2019 - 2024. All rights reserved.