I want to establish a relationship between two tables using a foreign key to read me the description (funzione string(40)). My models and code:
first model:
id: {
autoIncrement: true,
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true
},
id_user: {
type: Sequelize.INTEGER,
allowNull: false
},
id_role: {
type: Sequelize.INTEGER,
allowNull: false
},
id_funzione: {
type: Sequelize.INTEGER,
allowNull: false
}
}, {
sequelize,
tableName: 'abilitazioni',
schema: 'public',
timestamps: false,
indexes: [
{
name: "pk_abilitazioni",
unique: true,
fields: [
{ name: "id"},
]
},
]
Second model:
id: {
autoIncrement: true,
type: Sequelize.INTEGER,
allowNull: false,
primaryKey: true
},
funzione: {
type: Sequelize.STRING(40),
allowNull: false
}
}, {
sequelize,
tableName: 'funzioni',
schema: 'public',
timestamps: false,
indexes: [
{
name: "pk_funzioni",
unique: true,
fields: [
{ name: "id_funzione" },
]
},
]
The relation
db.Abilitazioni.hasOne(db.Funzioni, {
foreignKey: 'id_funzione'
});
db.Funzioni.belongsTo(db.Abilitazioni);
find on db
Abilitazioni.findAll({
where: { id_role: id
},
include: [{
Funzioni,
}]
})
I tried to create a one to one relationship to read a description field with the foreign key.
This query : SELECT funzioni.id , funzioni.funzione , funzioni.access_level from public.abilitazioni, public.funzioni where abilitazioni.id_user = 1 and id_role= 1 andabilitazioni.id_funzione = funzioni.id ;