gpt4 book ai didi

Node.js sequelize 创建对象虽然关联失败

转载 作者:行者123 更新时间:2023-12-03 22:32:18 25 4
gpt4 key购买 nike

我在 node.js 上使用 sequelize。
我的 Assets 模型对象:

module.exports =
class Asset extends Model {

static init(sequelize) {
return super.init(
{
AssetID: {
field: "asset_id",
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
AssetName: {
field: "asset_name",
type: DataTypes.STRING(40),
allowNull: false
},
SKU: {
field: "sku",
type: DataTypes.STRING(30)
}
},
Object.assign({
sequelize,
tableName: "assets",
})
);
}

static associate(models) {
Asset.Listings = this.hasMany(models.Listing,
{
as: 'Listings',
foreignKey: {name: 'AssetID', field: 'asset_id'},
sourceKey: 'AssetID'
})
}
};
list 定义是:
module.exports =
class Listing extends Model {
static init(sequelize) {
return super.init(
{
ListingID: {
field: "listing_id",
type: DataTypes.INTEGER(11),
allowNull: false,
primaryKey: true,
autoIncrement: true
},
IsPreferred: {
field: "isPreferred",
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
Price: {
field: "price",
type: DataTypes.DOUBLE(5,2),
allowNull: false,
validate: { min: 0 }
},
ListingType: {
field: "listing_type",
type: DataTypes.STRING(20),
allowNull: false,
defaultValue: "Buy",
validate: {
isIn: [['Buy', 'Rent']]
}
}
},
Object.assign({
sequelize,
tableName: "listings",
})
);
}
这是我的创建代码:
await Asset.create(newRecord, {include: [{ association: Asset.Listings } ]})
.then(dbRecord => {
logger.debug(`New Asset created`);
return dbRecord;
})
.catch(err => {
logger.warn(`Asset could not be created. ${JSON.stringify(newRecord)}`, err);
throw createServiceError(`Create Asset`, err);
})
现在...我的问题是,当我创建一个带有列表关联的新 Assets 记录时,如果列表的创建失败(例如在类型验证上,假设我输入了“abc”),列表将不会创建(因为值无效)但 Assets 已创建。
我希望整个交易将被恢复。
这有点奇怪,因为 create 调用在 catch 块中结束。
有任何想法吗?
谢谢,
阿萨夫

最佳答案

您可以使用事务。
抱歉格式化我正在通过电话给出答案。

sequelize.transaction(transaction => {
Asset.create(newRecord, {include: [{ association: Asset.Listings } ], transaction})
})
.then(function() {
console.log('success');
})
.catch(function(err) {
console.log(err);
})
})

关于Node.js sequelize 创建对象虽然关联失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65696733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com