SequelizeDatabaseError: 运算符不存在 uuid = integer

7

我正在尝试根据UUID(我也有ID)使两个表联接,这些表存在一些复杂的关系……

当我运行查询时,出现了错误。

第一个表名为users,它的UUID称为registry_uuid。 第二个表是beneficiaries,但这个表有两个UUID,分别是uuid_beneficiaryuuid_benefactor

为什么?因为第一个表有一个列user_type_id,通过此列我们可以知道它是用户beneficiary还是benefactor。 而第二个表则是用于确定哪些用户存在关联关系。

用户模型:

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"
}

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

1个回答

1

你应该首先检查你所包含的模型及其ID类型。它们必须具有相同的类型。此外,假设我们有用户(User)和角色(Role)模型。每个用户只能有一个角色,而一个角色可以被多个用户使用。在这种情况下,如果你写错了关联,就会出现这个错误。

错误版本:

// 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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接