I have a model Transaction with a hasMany association to StripePayment.
I want to create a new Transaction with a related StripePayment like so:
await models.Transaction.create({
amount,
stripePayment: {
stripeId: paymentIntent.id,
status: stripePaymentStatuses[status],
clientSecret: paymentIntent.client_secret,
}
});
This creates a new Transaction but does not create the stripePayment.
My model is as such:
// 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',
}
);
I feel like the model is not aware of stripePayment when I pass it into the create method. Am I structuring this correctly?
How can I create a Transaction with a related StripePayment?
You just need to indicate the include option while calling the create method, see 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',
}]
});