如何在 Sequelize 中定义 hasOne 关系?

How to define hasOne relationship in Sequelize?

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

当我运行以下查询时:

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

它试图在 Transaction`.`id` = `StripePayment`.`stripePaymentId 处进行左外连接,而本应相反。即 Transaction`.`stripePaymentId` = `StripePayment`.`id

我的 table 看起来像这样

交易

=======
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',
  }
);

我的印象是一对一关系应该在原点上有一个外键 table。

如何告诉 sequelize 在 transaction.stripePaymentId 上加入 === stripePayment.id

您应该使用具有 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'
    });
  }
}

请注意 foreignKeybelongsTo/hasOne(hasMany) 的选项值应该相同。