Reputation: 47
I have following models defined for Sequelize
const brand = sequelize.define('brands', {
brand_id: {
type: Sequelize.UUID,
primaryKey: true
},
name: Sequelize.STRING
}, {
timestamps: false,
underscored: true
});
const model = sequelize.define('models', {
model_id: {
type: Sequelize.UUID,
primaryKey: true
},
name: Sequelize.STRING
}, {
timestamps: false,
underscored: true
});
model.belongsTo(brand, {foreignKey: 'brand_id'});
I use this code to query the database
model.findOne({
raw: true,
where: {name: 'TIPO'},
include: brand})
.then(car => {
console.log(car);
});
And it returns the rows formatted like this
{ model_id: '7e5a29ba-05b1-45f7-9fee-41f8440fe975',
name: 'TIPO',
brand_id: 'f3e4962c-906f-46c4-b992-7375ab46002a',
'brand.brand_id': 'f3e4962c-906f-46c4-b992-7375ab46002a',
'brand.name': 'FIAT' }
While I would really like for it to look more like this
{ model_id: '7e5a29ba-05b1-45f7-9fee-41f8440fe975',
model_name: 'TIPO',
brand_name: 'FIAT' }
Is there a way to achieve make it work like this?
Upvotes: 0
Views: 633
Reputation: 41
You need to use the attributes option
model.findOne({
raw: true,
where: {name: 'TIPO'},
include: {
model: model.brand,
attributes: [ 'name' ], // represents brand.name
}
})
.then(car => {
const newCar = car;
// if you want to change/rename the object properties around, do so here via newCar
console.log(newCar);
});
You may want to consider changing "name" in the brand model to bName or brandName to avoid confusion.
Upvotes: 1