[英]nodejs sequelize hasOne association not working
in my nodejs app where i am using sequelize to reach to database i have some tables called (Products , Users , Carts , CartItems)在我使用 sequelize 访问数据库的 nodejs 应用程序中,我有一些名为(Products、Users、Carts、CartItems)的表
and there is this relationship between them他们之间有这种关系
Product.belongsTo(User, { constraints: true, onDelete: 'CASCADE' });
User.hasMany(Product);
User.hasOne(Cart);
Cart.belongsTo(User);
Cart.belongsToMany(Product, { through: CartItem });
Product.belongsToMany(Cart, { through: CartItem });
as you see user can only have one cart but where i use createCart();如您所见,用户只能拥有一辆购物车,但我使用 createCart(); function it can make more than one carts功能它可以制作不止一辆手推车
sequelize
// .sync({ force: true })
.sync()
.then(result => {
return User.findByPk(1);
// console.log(result);
})
.then(user => {
if (!user) {
return User.create({ name: 'Max', email: 'test@test.com' });
}
return user;
})
.then(user => {
// console.log(user);
return user.createCart();
})
.then(cart => {
app.listen(4000);
})
.catch(err => {
console.log(err);
});
this code is in my app.js file and every time server reloads it checks if there is not a user it makes it but createCart();这段代码在我的 app.js 文件中,每次服务器重新加载时,它都会检查是否没有创建它的用户,而是 createCart(); which sequelize should handle that to not be more than one cart for each user , that doesn't works correctly and everytime server reloads it makes another cart for user哪个续集应该处理每个用户不超过一个购物车,这不能正常工作,每次服务器重新加载时它都会为用户制作另一个购物车
Is the id of user a unique key or primary key in your cart table?用户的 id 是购物车表中的唯一键还是主键? i think it should be, and your keys should be defined in those relationships i think... something like so..我认为它应该是,并且你的密钥应该在我认为的那些关系中定义......像这样......
User.hasOne(Cart, { as: 'Cart', sourceKey: 'id', foreignKey: 'user_id' }); User.hasOne(Cart, { as: 'Cart', sourceKey: 'id', foreignKey: 'user_id' }); Cart.belongsTo(User, { as: 'CartOwner', sourceKey: 'user_id', foreignKey: 'id' }); Cart.belongsTo(User, { as: 'CartOwner', sourceKey: 'user_id', foreignKey: 'id' });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.