javascript - SequelizeDatabaseError: 运算符不存在 uuid = integer
问题描述
我正在尝试与基于 UUID 的两个表(我也有 id)进行连接,这些表有一些困难的关系......
当我运行查询时,我得到了错误。
第一个表称为users,他的 UUID 称为registry_uuid。第二个表受益人,但此表有两个 UUID,uuid_beneficiary和uuid_benefactor。
为什么?因为第一个表有一个列user_type_id并且我们可以知道它是用户受益人还是受益人。第二张表是要知道哪些用户是相关的。
模型用户:
const User = sequelize.define('users', {
registry_uuid: {
type: Sequelize.UUIDV4,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
user_type_id: {
type: Sequelize.INTEGER,
defaultValue: 1,
allowNull: false
}
}
示范受益人:
const Beneficiary = sequelize.define('beneficiaries', {
uuid_benefactor: {
type: Sequelize.UUIDV4,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
uuid_beneficiary: {
type: Sequelize.STRING,
defaultValue: Sequelize.UUIDV4,
allowNull: false
},
created_at: {
type: Sequelize.DATE,
defaultValue: Sequelize.NOW
},
disassociation_date: {
type: Sequelize.DATE,
defaultValue: null
}
}
查询:
async function getBenefactorOfBeneficiary (benefactorUuid, arrayAttributes) {
arrayAttributes = arrayAttributes || ['registry_uuid', 'name', 'last_name', 'picture']
return UserModel.findOne({
where: {
registry_uuid: {
[Op.eq]: benefactorUuid
}
},
include: [{
model: BeneficiaryModel,
}],
attributes: arrayAttributes,
raw: true
})
}
关系:
UserModel.hasMany(beneficiaryModel, {foreignKey: 'uuid_benefactor'})
beneficiaryModel.belongsTo(UserModel, {foreignKey: 'registry_uuid'})
我期望输出:
例子:
{
"name": "string",
"lastName": "string",
"picture": "string",
"created_at" "string"
}
显然我修改了控制器中的响应
解决方案
您应该首先检查您所包含的模型及其 ID 类型。它们必须具有相同的类型。除此之外,假设我们有用户和角色模型。每个用户只能有一个角色,一个角色可以被多个用户使用。在这种情况下,如果你写错了关联,你会得到这个错误。
错误版本:
// Under the user model associations
user.hasOne(models.role, { foreignKey: "roleId" });
// this will try to compare your userId with roleId of Role table
// Under the Role model associations
role.hasMany(models.user, { foreignKey: "roleId" });
正确的版本应该是这样的:
// Under the user model associations
user.hasOne(models.role, { foreignKey: "roleId" });
// this will try to compare your roleId from User model with roleId of Role table
// Under the Role model associations
role.hasMany(models.user, { foreignKey: "roleId" });
如果您需要更多详细信息,请阅读https://sequelize.org/master/manual/assocs.html
推荐阅读
- javascript - 在 AJAX 成功调用中保存变量以传入另一个 AJAX 成功调用
- c++11 - 如何保存结构向量中的数据并在程序启动时加载它?
- arangodb - 如何将图形数据批量加载到 ArangoDB
- r - R 中 LOOCV 拆分的线性回归返回错误
- javascript - 将响应传递给 addEventListener 中的函数
- jquery - 无法从 JSON 文件中读取图像
- c# - 如何让动态创建的用户控件显示?
- azure - SPA 应用程序(Angular5)如何访问单独的 WebAPI(在 AzureAD 下)
- php - 在子字符串文本描述中添加点
- python-3.x - 如何从 python3.7.1 运行 pip