musztardus
musztardus

Reputation: 47

Sequelize format of join query response

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

Answers (2)

Reventlow
Reventlow

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

KenOn10
KenOn10

Reputation: 1968

You need to add attributes to both model and brand... without these, you will see all fields (e.g. SELECT *). Take a look at the doc

Upvotes: 0

Related Questions