【问题标题】:Node.js & SQL Server Sequelize joining tableNode.js 和 SQL Server Sequelize 加入表
【发布时间】:2018-06-22 18:33:59
【问题描述】:

我尝试将列设置为外键,但出现错误

未处理的拒绝 SequelizeForeignKeyConstraintError:MERGE 语句与 FOREIGN KEY 约束“FK__Wishlists__produ__03C67B1A”冲突。冲突发生在数据库“database”、表“dbo.posts”、列“productid”中。

cart_table 中的外键名称为 productidproduct_table 中的主键名称为 productid

Cart.belongsTo(Product, {foreignKey: 'productid', targetKey: 'productid'});

这是正确的方法吗?

场景:

  • 用户将商品添加到购物车。
  • 购物车表将添加商品信息:用户名(添加者)、productid(与 produc_table 中的 productid{primaryKey} 相同)

我会通过将 cart_table 与 product_table 连接来操作数据,这样结果将是:

cart_product_table

username: alex
cart_table.productid: 01
product_table.productid: 01
productName: Shampoo
productPrice: 12

【问题讨论】:

  • 您的购物车表中有记录吗?
  • @Priyank 是的,我愿意。当用户点击添加按钮时,它会添加一条新记录,其中包含:productid, username
  • @Priyank 我想根据 productid 组合两个表。购物车表中的productid为外键,产品表中的productid为主键。
  • 更改 Cart.belongsTo(Product, {foreignKey: 'productid', targetKey: 'productid'}); TO Cart.belongsTo(Product, {foreignKey: 'productid', targetKey: 'productid',defaultValue : 0});
  • 让我知道仍然没有工作

标签: sql node.js sequelize.js


【解决方案1】:

正如评论中所讨论的,您的购物车中有数据,因此您遇到了错误。

Cart.belongsTo(Product, {foreignKey: 'productid', targetKey: 'productid'}); 

用这个改变这个代码。

Cart.belongsTo(Product, {
     foreignKey: 'productid', 
     targetKey: 'productid',
     defaultValue : 0
});

您只需添加默认值

【讨论】:

    【解决方案2】:

    根据您的情况,您正在将ProductCart 进行一对一映射。

    您将购物车与产品关联为,

    Cart.belongsTo(Product, {
        foreignKey: 'productid',
        targetKey: 'productid'
    });
    

    同样,您也必须将 Product 关联到购物车。

    Product.belongsTo(Cart, {
        foreignKey: 'productid',
        sourceKey: 'productid'
    });
    

    【讨论】:

      猜你喜欢
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 2016-12-30
      • 2011-07-06
      • 2018-02-12
      • 2021-10-09
      • 1970-01-01
      相关资源
      最近更新 更多