簡體   English   中英

如何在 Sequelize 中定義 hasOne 關系?

[英]How to define hasOne relationship in Sequelize?

我有一筆transaction model 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

您應該從具有foreign key字段和hasOnehasMany的 model 中使用belongsTo作為父 model ,另一個 model 具有引用(外鍵)。
此外,如果外鍵列的名稱不是<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'
    });
  }
}

請注意,對於belongsTo/hasOne(hasMany)對, foreignKey選項值應該相同。

暫無
暫無

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

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