【发布时间】: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