簡體   English   中英

nodejs 續集 hasOne 關聯不起作用

[英]nodejs sequelize hasOne association not working

在我使用 sequelize 訪問數據庫的 nodejs 應用程序中,我有一些名為(Products、Users、Carts、CartItems)的表

他們之間有這種關系

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 });

如您所見,用戶只能擁有一輛購物車,但我使用 createCart(); 功能它可以制作不止一輛手推車

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);
    });

這段代碼在我的 app.js 文件中,每次服務器重新加載時,它都會檢查是否沒有創建它的用戶,而是 createCart(); 哪個續集應該處理每個用戶不超過一個購物車,這不能正常工作,每次服務器重新加載時它都會為用戶制作另一個購物車

用戶的 id 是購物車表中的唯一鍵還是主鍵? 我認為它應該是,並且你的密鑰應該在我認為的那些關系中定義......像這樣......

User.hasOne(Cart, { as: 'Cart', sourceKey: 'id', foreignKey: 'user_id' }); Cart.belongsTo(User, { as: 'CartOwner', sourceKey: 'user_id', foreignKey: 'id' });

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM