How to get join data result without prefix table name in Sequelize ORM
This should work
A
is a table that is associated to B
using a column called bId
so B has a primary key of Id
which is associates to a bid
column in A
table that is shown in the standard result set as b.id
but we want these two column to be called as Id & Name
A.belongsTo(B);
return await A.findAll({
attributes: [
[Sequelize.col('b.id'), 'Id'],
[Sequelize.col('b.name'), 'Name']
],
raw: true,
where: { /*Some condition*/ },
include: {
model: B,
attributes: [],
required: true
},
});
The top level model also can be modified to exclude and include the properties if the query still want to use along with
raw: true
db.admin.findAll({
include: [{
model: db.role,
where:{status : 'Active'},
attributes: ["role_id", "role_name"],
nested: false,
}],
attributes: {exclude: [],
include: ["role.role_id", "role.role_name"]},
raw: true
});
additionally you can have aliases as well
db.admin.findAll({
include: [{
model: db.role,
where:{status : 'Active'},
attributes: [["role_id", "roleId"], ["role_name", "roleName"]]
}],
attributes: {exclude: [],
include: ["role.roleId", "role.roleName"]},
raw: true
});
This should work,
db.admin.findAll({
attributes: ['id', 'username', 'email', 'status', 'role.role_id', 'role.role_name'],
include: [{
model: db.role,
where:{status : 'Active'},
attributes: []
}],
raw: true
})
I found this here