我可以将数据插入表中,除了一个带有外键(userId)的字段
这是我的购物车型号
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;
我希望我可以完全插入该字段
您应该在两个配对关联中指示相同的
foreignKey
选项,请参阅我的 asnwer 此处
CartModel.belongsTo(UserModel, {
foreignKey: "userId" })
UserModel.hasMany(CartModel, {
foreignKey: "userId",
onDelete: "cascade",
onUpdate: "cascade"
})