【问题标题】:How to save entry in Sequelize with hasOne relationship?如何使用 hasOne 关系保存 Sequelize 中的条目?
【发布时间】:2022-01-28 05:30:12
【问题描述】:

我有一个模型 TransactionhasMany 关联到 StripePayment

我想用相关的StripePayment 创建一个新的Transaction,如下所示:

await models.Transaction.create({
  amount,
  stripePayment: {
    stripeId: paymentIntent.id,
    status: stripePaymentStatuses[status],
    clientSecret: paymentIntent.client_secret,
  }
});

这会创建一个新的交易,但不会创建 stripePayment。

我的模型是这样的:

// transaction model
class Transaction extends Model {
    
  static associate(models) {
    this.hasOne(models.StripePayment, { 
      as: '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',
      },
    },
    amount: {
      type: DataTypes.INTEGER,
      allowNull: false,
    }
  },
  {
    sequelize,
    modelName: 'Transaction',
  }
);
// stripePayment
class StripePayment extends Model {
    
  static associate(models) {
    this.belongsTo(models.Transaction, { 
      as: 'Transaction', 
      foreignKey: 'stripePaymentId' 
    });
  }
}

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

当我将它传递给create 方法时,我觉得模型不知道stripePayment。我的结构正确吗?

如何使用相关的StripePayment 创建Transaction

【问题讨论】:

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


    【解决方案1】:

    您只需要在调用create 方法时指明include 选项,参见creating with associations

    await models.Transaction.create({
      amount,
      // pay attention: this prop should be named exactly as an alias of a model and because it's `hasMany` you should wrap it into an array
      StripePayment: [{
        stripeId: paymentIntent.id,
        status: stripePaymentStatuses[status],
        clientSecret: paymentIntent.client_secret,
      }],
      include: [{
        model: StripePayment,  
        as: 'StripePayment',
      }]
    });
    

    【讨论】:

    • 谢谢,我已经尝试添加,但仍然得到相同的结果 - 没有创建 StripePayment。我已确保密钥也与模型的别名匹配,正如您所拥有的那样,它是 StripePayment。我在Transaction 模型中的外键是stripePaymentId 是否重要?是否应该使用新创建的 stripePayment.id 值自动填充?
    • 看看更新的答案,你有hasMany所以你需要使用一个数组
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-22
    • 2013-10-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多