sequelize中如何设置一对一和多对多关系

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

我有一个三表用户、产品、购物车的模型。现在我希望一排购物车只属于一个用户。但是一排购物车可以有很多产品。 sequelize 文档没有太多关于 setter 和 getter 的细节,否则我很困惑。下面是我的代码,它可以创建用户,但购物车不是同时创建的,没有购物车我就不能把产品放进去。

// this is my assosiation
let db = {};


db.user = require("./user");
db.cart = require("./cart");
db.product = require("./product")


db.user.hasOne(db.cart);
db.cart.belongsTo(db.user);
db.product.belongsToMany(db.cart,{
    through:"product_cart",
    foreignKey : "productId",
    otherKey: "cartId"
});
db.cart.belongsToMany(db.product,{
    through:"product_cart",
    foreignKey:"cartId",
    otherKey:"productId"
})
// this is my user controller

let user = db.user;

let addUser = async function (req,res,next){
 let {name,email,password} = req.body;
 if(!name) return res.status(404).send("name is required")
 if(!email) return res.status(404).send("email is required")
 if(!password) return res.status(404).send("password is required")
    await user.create({
        name:name,
        email:email,
        password:password
    })

    res.status(200).send("user added");
    res.end();
}
// it is my cart controller

let addPorductIncart = async (req,res,next)=>{
    let user = await db.user.findByPk(req.params.userId)
    if(!user) return res.status(404).send("no user found");
    
    let product = await db.product.findByPk(req.body.id)

    if(!product) return res.status(404).send("no product found");

    let cart = await db.cart.findOne({
        where:{
            userId:req.params.userId
        }
    })
    if(!cart) await user.setCart(cart)
    cart = await db.cart.findOne({
        where:{
            userId:req.params.userId
        }
    })
    await cart.setProduct(product);
    let totalCost = cart.totalPrice;
    totalCost += product.price;
    await db.cart.update({totalPrice:totalCost},
        {
            where:{
                userId:userId
            }
        })
        res.status(200).send("product added").end();
}

我试图建立联系但没有成功

mysql node.js sequelize.js associations relationship
1个回答
0
投票

在两个代码工作之后创建一对一的关系

就像你有用户和购物车,一个购物车只属于一个用户

User.hasOne(Cart)

这表明用户只有一个购物车,因此 userId 将自动分配给购物车表,以跟踪哪个购物车属于哪个用户。

所以如果你使用下面的代码

cart.hasOne(user)

这意味着一个购物车只能有一个用户,所以 cartId 将被分配到用户表中,但我们已经在购物车中有一个 userId 列为什么不只使用它来跟踪用户和购物车 所以我们可以使用之前分配的 userId

Cart.belongTo(User)

表示不会生成新的id

一对一关联表的使用方式

提供了一些方法来使用关联表,如 set 和 get

假设你有两个表用户和购物车有一些用户 但是购物车表中没有购物车行,所以没有关系 用户和购物车之间 首先设置表之间的关系

User.hasOne(Cart)
Uart.belongTo(User)

现在首先您必须先创建购物车,然后再将其分配给用户

   let cart =  await Cart.create() // here Cart is model of cart

现在首先我们必须从用户表中选择一个用户

   let user await Users.findOne({where:{id:userId}})

设置所选用户和创建的购物车之间的关系

await user.addCart(cart) // here cart  is the cart that we created and user that we selected 

如果购物车已经可用但未分配给任何用户怎么办 比起我们先选择那个购物车并应用设置方法

let cart = await Cart.findOne({where:{id:cartId}})
await user.addCart(cart)

选择用户购物车我们可以使用用户获取方法

user.getCarts();

要设置一对多之间的关系,我们可以使用 belongToMany 方法 假设在一个用户和地址表中,一个用户可以有多个表,但一个地址不能有多个用户

User.hasMany(Address) // new userId column created in Address table
Address.belongTo(User) // tells that one address can be of one user only

如果你想给用户分配地址而不是使用

await user.addAddress(address) // address => particular present row in Address table not whole Address table // user => paticular selected person not table

如果你想给一个用户分配很多地址比

await user.setAddresses([{},{},{}]) // object are address from the address table 

获取地址

await user.getAddresses();

还有很多其他方法可以使用它们

同样的小复杂事物适用于多对多关系

小心使用单数和复数的东西,它搞砸了续集 set 和 get 方法只接受复数大腿,如 setAddresses setcarts setPeople getAddress 等,但 add 接受单数和复数,如 addAddress 和 addAddress 两者具有不同的含义,同样的方式 addPeople,addPerson

© www.soinside.com 2019 - 2024. All rights reserved.