方法 set/add 不是函数 sequelize node js

Method set/add is not a function sequelize node js

我有 3 个 tables,订单,产品和枢轴 table,order_products,table 订单和产品有多对多的关系,但是当我尝试使用方法时

order.addProduts()

不工作,return错误

UnhandledPromiseRejectionWarning: TypeError: Order.addProducts is not a function

但是我已经验证了我的产品和订单模型,关系没问题,我没有看到任何错误

我尝试使用该方法时的模型和控制器:

class Products extends Model {
    static init(sequelize) {
        super.init({
            name: DataTypes.STRING,
            price: DataTypes.FLOAT,
            description: DataTypes.STRING
        },{
            sequelize
        })
        
    }
    static associate(models){
        this.belongsToMany(models.Orders, {as: 'order_product', foreignKey: 'product_id', through: 'order_products'})
    }
}
module.exports = Products;


class Orders extends Model {
    static init(sequelize) {
        super.init({
            name: DataTypes.STRING,
            street: DataTypes.STRING,
            phonenumber: DataTypes.STRING,
            number: DataTypes.STRING,
            reference: DataTypes.TEXT,
            note: DataTypes.TEXT,
         

        }, {
            sequelize,
        })
    }
    static associate(models){
        this.belongsToMany(models.Products, {as: 'product_order', foreignKey: 'order_id', through: 'order_products'})
    }

}

我的控制器

async store (req, res){
        const {name, phonenumber, street, number, reference, note, value_subtotal, value_delivery, value_total, products} = req.body;
        if(!(name|| phonenumber || value_subtotal || value_total))return res.status(406).send({message: 'missing data!'})
        if((value_total|| value_subtotal) <= 0)return res.status(406).send({message: "total value or subtotal value can't be 0 or less than"})

        //console.log(products)
        const Order = await Orders.create({
            name, 
            phonenumber, 
            street,
            number,
            reference,
            note,
            value_subtotal,
            value_delivery,
            value_total
        })
        await Order.addProducts(products)
        return res.status(201).json(Order);
    },
not confirmend but i think you are using Order.addProducts() instead of order.addProduts();

您可以尝试通过这样做来实现相同的行为:

Order.create({
   name,
   Product: {...}
},{
   include: Product
})

或尝试 srequlize 文档中的示例:Creating with associations