我有两个桌子。用户和产品。它们通过称为Carts的表关联。它增加了一个称为“数量”的列。
这会将用户与产品和数量相关联,我将从中获取其“购物车”。
我不知道如何使用User.setProducts()。每次尝试时,都会显示错误:quantity.cart不能为null。
购物车表
const Cart = db.define('cart', {
quantity: {
type: Sequelize.INTEGER,
allowNull: false
}
})
用户表
const User = db.define('user', {
email: {
type: Sequelize.STRING,
unique: true,
allowNull: false
},
password: {
type: Sequelize.STRING,
// Making `.password` act like a func hides it when serializing to JSON.
// This is a hack to get around Sequelize's lack of a "private" option.
get() {
return () => this.getDataValue('password')
}
}
}
产品表
const Product = db.define('product', {
name: {
type: Sequelize.STRING,
allowNull: false
},
description: {
type: Sequelize.TEXT,
allowNull: false
}
}
关联
User.belongsToMany(Product, {through: 'cart'})
Product.belongsToMany(User, {through: 'cart'})
我基本上想做什么:
let myUser = await User.findByPk(1);
myUser.setProducts([{productId: 1, cart: {quantity: 4}}, product2,3...etc])
我尝试了许多不同的格式,没有用。我也很好奇是否有办法更新此表上的关联。假设存在一个产品编号为1,用户编号为2且数量为3的商品。是否有办法获取它并将其数量设为5?
谢谢大家的帮助。我已经进行了很多次谷歌搜索,但是我无法确定这是否可行。