【问题标题】:How to define hasOne relationship in Sequelize?如何在 Sequelize 中定义 hasOne 关系?
【发布时间】:2022-01-29 01:04:31
【问题描述】:

我有一个 transaction 模型 hasOne stripePayment。我希望能够检索与其关联的 stripePayment 的交易。

当我运行以下查询时:

const data = await models.Transaction.findOne({
  where: { clientId },
  include: [
    {
      model: models.StripePayment,
    }
  ]
});

它试图将外部连接留在Transaction`.`id` = `StripePayment`.`stripePaymentId 的位置,而它应该是相反的。即Transaction`.`stripePaymentId` = `StripePayment`.`id

我的桌子看起来像这样

交易

=======
id  |  stripePaymentId     
---------------------
1   |  1a
2   |  2b
3   |  3c
4   |  4d

条纹支付

=======
id   |  amount     
---------------------
1a   |  100
2b   |  101
3c   |  102
4d   |  103

然后我的模型具有这样定义的关联:

class Transaction extends Model {
  static associate(models) {
    this.hasOne(models.StripePayment, {
      foreignKey: 'id'
    });
  }
}

Transaction.init(
  {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    stripePaymentId: {
      type: DataTypes.UUID,
      allowNull: true,
      foreignKey: true,
      references: {
        model: stripePayment,
        key: 'id',
      },
    }
  },
  {
    sequelize,
    modelName: 'Transaction',
  }
);

class StripePayment extends Model {
  static associate(models) {
    this.belongsTo(models.Transaction, {
      foreignKey: 'stripePaymentId'
    });
  }
}

StripePayment.init(
  {
    id: {
      allowNull: false,
      primaryKey: true,
      type: DataTypes.UUID,
      defaultValue: DataTypes.UUIDV4,
    },
    amount: {
      type: DataTypes.INTEGER,
      allowNull: false,
    }
  },
  {
    sequelize,
    modelName: 'StripePayment',
  }
);

我的印象是一对一关系应该在源表上有一个外键。

如何让 sequelize 加入 transaction.stripePaymentId === stripePayment.id

【问题讨论】:

    标签: javascript mysql node.js orm sequelize.js


    【解决方案1】:

    您应该使用具有foreign key 字段的模型中的belongsTohasOnehasMany 作为另一个模型引用的父模型(外键)。
    此外,如果外键列的名称不是<Child table mode>+<id>,则在定义关联时应指明foreignKey 选项。

    class Transaction extends Model {
      static associate(models) {
        this.belongsTo(models.StripePayment, {
          foreignKey: 'stripePaymentId'
        });
      }
    }
    ...
    class StripePayment extends Model {
      static associate(models) {
        this.hasOne(models.Transaction, {
          foreignKey: 'stripePaymentId'
        });
      }
    }
    

    请注意,foreignKey 选项值对于 belongsTo/hasOne(hasMany) 对应相同。

    【讨论】:

    • 谢谢。看来我确实在模型中确实存在错误的关系。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-05
    • 2016-05-20
    • 1970-01-01
    • 1970-01-01
    • 2016-06-11
    • 1970-01-01
    相关资源
    最近更新 更多