我正在尝试使用基于uuid的两个表(我也有ID(加入,这些表有一些困难的关系...
当我运行查询时,我会收到错误。
第一个表被称为用户,他的UUID称为 impristry_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