【发布时间】:2022-02-04 05:41:56
【问题描述】:
我想创建两行。
首先我想创建一个tenant,然后我想创建一个引用tenant的user。
我想在一个事务中完成此操作(注册)。
tenant 将被创建,但是当 sequelize 尝试创建用户时,我得到一个错误:
Failing row contains
例程:ExecConstraints
我的数据库映射:
const TenantMapping = sequelize.define('tenant', {
id: { type: DataTypes.NUMBER, primaryKey: true, autoIncrement: true },
label: { type: DataTypes.STRING, allowNull: false },
name: { type: DataTypes.STRING },
postOfficeBox: { type: DataTypes.STRING },
street: { type: DataTypes.STRING },
houseNo: { type: DataTypes.STRING },
zipCode: { type: DataTypes.STRING, validate: { max: 10 } },
city: { type: DataTypes.STRING },
phone: { type: DataTypes.STRING },
mobilePhone: { type: DataTypes.STRING },
email: { type: DataTypes.STRING, allowNull: false },
website: { type: DataTypes.STRING },
birth: { type: DataTypes.DATE, allowNull: false },
death: { type: DataTypes.DATE }
}, {
...getSequelizeTableSettings({ schema: 'auth' })
});
const UserMapping = sequelize.define('user', {
id: { type: DataTypes.NUMBER, primaryKey: true, autoIncrement: true },
tenantId: { type: DataTypes.NUMBER, allowNull: false },
email: { type: DataTypes.STRING, allowNull: false },
password: { type: DataTypes.STRING, allowNull: false },
role: { type: DataTypes.STRING, allowNull: false },
isActivated: { type: DataTypes.BOOLEAN, allowNull: false },
birth: { type: DataTypes.DATE, allowNull: false },
death: { type: DataTypes.DATE }
}, {
...getSequelizeTableSettings({ schema: 'auth' })
});
我的控制器
const response = await sequelize.transaction(async (transaction) => {
try {
const { tenantLabel, email, password } = req.body;
const tenant = await this.tenantRepository.create({
tenantLabel,
email
}, {
transaction
});
const user = await this.userRepository.create({
email,
password,
tenantId: tenant.id,
role: UserRole.ADMIN
}, {
transaction
});
await transaction.commit();
res.status(200).json({
tenant,
user
});
} catch (exception) {
res.status(400).send({
...exception
});
}
});
如果我在两个不同的transactions 中创建tenant 和user - 它工作正常。
怎么了?
【问题讨论】:
-
如果你使用像
sequelize.transaction(async (transaction) => {这样的回调打开一个事务,那么你不需要显式调用commit -
你使用什么数据库?您能否添加有关该错误的更多信息?
-
我在线程中添加了更多细节。有什么想法吗?
-
你能显示
tenantRepository和userRepository的代码吗? -
我发布了
tenantRepository、userRepository和父Repository
标签: node.js sequelize.js