【问题标题】:Sequelize: Associating two columns in one table. After i added my associations i am getting an error when inserting a rowSequelize:在一个表中关联两列。添加关联后,插入行时出现错误
【发布时间】:2021-03-05 17:53:33
【问题描述】:

提前致谢!

所以每次我尝试在表中插入新行时都会出错。在我添加我的关联之前,我在邮递员中测试了我的表和我的创建函数,并且能够成功地插入到表中。问题只有在我添加了我的关联后才出现。这是我的表格和关联

id | userOneId | userTwoId | status | actionUserId |         createdAt          |         updatedAt          

这里是关联

  models.relationship.belongsTo(models.user,  {as:"userOne", foreignKey:"userOneId"})
  models.relationship.belongsTo(models.user,  {as:"userTwo", foreignKey:"userTwoId"})
  models.user.hasMany(models.relationship, {as:"userOne", as:"userTwo"})

一旦我添加了关联,每次我尝试插入新行时,我都会从数据库中收到此消息,然后在最后出现错误

执行(默认):INSERT INTO "relationships" ("id","userOneId","userTwoId","status","createdAt","updatedAt") VALUES (DEFAULT,$1,$2,$3,$4, $5) 返回 "id","userOneId","userTwoId","status","actionUserId","createdAt","updatedAt","userId"; DatabaseError [SequelizeDatabaseError]:列“userId”不存在

我的 catch 语句也暗示了

code: '42703',
hint: 'Perhaps you meant to reference the column "relationships.userOneId" or the column "relationships.userTwoId".',

【问题讨论】:

    标签: node.js express sequelize.js psql


    【解决方案1】:

    因此,在 Sequelize 文档中进行更多挖掘后,我发现了问题所在。不得不从与用户的关系中翻转外键

    models.relationship.belongsTo(models.user, {as:"userOne",}) models.relationship.belongsTo(models.user, {as:"userTwo",})

      models.user.hasMany(models.relationship, {foreignKey:"userOneId", foreignKey:"userTwoId"})
    

    【讨论】:

      猜你喜欢
      • 2019-04-14
      • 1970-01-01
      • 2016-04-11
      • 2018-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-14
      • 2021-05-12
      相关资源
      最近更新 更多