问题
I am using sequelize ORM in node js. I am join two table and get result but that result return with table name as prefix.
var Sequelize = require('sequelize');
var sequelize = new Sequelize('test', 'root', '', {
// configuration
}
});
const db = {};
db.Sequelize = Sequelize;
db.sequelize = sequelize;
db.role = require('./../model/definitions/role')(sequelize, Sequelize);
db.admin = require('./../model/definitions/admin')(sequelize, Sequelize);
db.admin.findAll({
include: [{
model: db.role,
where:{status : 'Active'},
}],
raw: true
}).then(function(result) {
console.log(result);
}).catch(function(error) {
console.log(error);
}).done();
Now I am getting this result:
[{
"id": 36,
"email": "test@gmail.com",
"username": "test",
"status": "Active",
"role.role_id": 1,
"role.role_name": "Admin"
}]
but I need this result:
[{
"id": 36,
"email": "test@gmail.com",
"username": "test",
"status": "Active",
"role_id": 1,
"role_name": "Admin"
}]
so, how to remove prefix table name 'role' from column. I have only need 'role_id' or 'role_name' not need this type data like 'role.role_id', 'role.role_name'
回答1:
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
回答2:
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
});
回答3:
raw: true , causes the issue while returning data with associations , solution to this is :
Remove :
raw: true
From :
db.admin.findAll({
include: [{
model: db.role,
where:{status : 'Active'},
}],
raw: true // <--------- Remove this
})
来源:https://stackoverflow.com/questions/50148491/how-to-get-join-data-result-without-prefix-table-name-in-sequelize-orm