我无法使用外键将字段插入到 Sequelize 中的表中

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

我可以将数据插入表中,除了一个带有外键(userId)的字段

cart table data

这是我的购物车型号

const CartModel = db.define("cart", {
    status: {
        type: DataTypes.STRING
    },
    totalPrice: {
        type: DataTypes.INTEGER
    }
}, {
    freezeTableName: true
})

CartModel.belongsTo(UserModel)
UserModel.hasMany(CartModel, {
    foreignKey: "userId",
    onDelete: "cascade",
    onUpdate: "cascade"
})
export default CartModel

这是我的 addToCart 函数

export const addToCart = async (req, res) => {
    const { userId} = req.body;

    try {

        const newCart = await CartModel.create({
            userId: userId,
            status: 'active'
        });

        res.status(200).json({
            msg: 'Item added to cart successfully',
            newCart
        });
    } catch (error) {
        console.error('Error adding item to cart:', error);
        res.status(400).json({msg: 'Failed to add item to cart'});
    }
};

这是路线

router.post("/v1/addToCart/", addToCart)

export default router;

这是我发布的内容 enter image description here

我希望我可以完全插入该字段

node.js express sequelize.js
1个回答
0
投票

您应该在两个配对关联中指示相同的

foreignKey
选项,请参阅我的 asnwer 此处

CartModel.belongsTo(UserModel, {
    foreignKey: "userId" })
UserModel.hasMany(CartModel, {
    foreignKey: "userId",
    onDelete: "cascade",
    onUpdate: "cascade"
})
© www.soinside.com 2019 - 2024. All rights reserved.