首页 > 解决方案 > SequelizeDatabaseError: 运算符不存在 uuid = integer

问题描述

我正在尝试与基于 UUID 的两个表(我也有 id)进行连接,这些表有一些困难的关系......

当我运行查询时,我得到了错误。

第一个表称为users,他的 UUID 称为registry_uuid。第二个表受益人,但此表有两个 UUID,uuid_beneficiaryuuid_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"
}

显然我修改了控制器中的响应

标签: javascriptnode.jspostgresqlsequelize.js

解决方案


您应该首先检查您所包含的模型及其 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


推荐阅读