I'm trying to make a join with two tables based on UUID (I have id too), those tables have some difficult relations...
When I run the query I get the error.
The first table is called users, and his UUID is called registry_uuid. The second table beneficiaries but this table has two UUID, uuid_beneficiary and uuid_benefactor.
Why? because the first table has a column user_type_id and with this we can know if it's a user beneficiary or benefactor. And the second table is to know which users are related.
Model Users:
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
}
}
Model Beneficiaries:
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
}
}
Query:
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
})
}
Relation:
UserModel.hasMany(beneficiaryModel, {foreignKey: 'uuid_benefactor'})
beneficiaryModel.belongsTo(UserModel, {foreignKey: 'registry_uuid'})
I expect the output:
Example:
{
"name": "string",
"lastName": "string",
"picture": "string",
"created_at" "string"
}
obviously I modify the response in controller