Robin Claes
Robin Claes

Reputation: 502

Sequelize include as property instead of node

In Sequelize, is there a proper way to do a query with an include, but instead of showing the included entity in a node, showing the included entity properties with the main models properties?

Example:

// Project belongsTo Customer

Project.findAll({
  include: [{
      model: Customer
  }]
})

Actual result:

{
  name: 'Project X',
  customer: {
   name: 'Customer Y',
   street: 'Paddington street'
  }
}

Expected result:

{
  name: 'Project X',
  customer_name: 'Customer Y',
  customer_street: 'Paddington street'
}

Upvotes: 3

Views: 1318

Answers (2)

ScottS
ScottS

Reputation: 72261

I know this is an old question, but I had a similar question and found a Sequelize solution. So for the OP's example, the solution would be this:

Project.findAll({
  attributes: [
    [sequelize.col('Customer.name'), 'customer_name'],
    [sequelize.col('Customer.street'), 'customer_street'],
  ],
  include: [{
     model: Customer,
     attributes: [], // Make sure no nested attributes are returned
  }]
})

Upvotes: 0

PhilippeAuriach
PhilippeAuriach

Reputation: 2447

I dont think there is a way of doing this with Sequelize. I would suggest getting your result as this, then iterating over your result to rename your properties (using Object.keys for example) :

Project.findAll({
    include: [{
        model: Customer
    }]
}).then(projects => {
    return projects.map(project => {
        Object.keys(project.customer).forEach(key => {
            project['customer_' + key] = project.customer[key];
        })
        delete project.customer;
        return project;
    })
}) 

If you really need to have your result right from the db, you could eventually make a raw query, but then you'll loose the benefits of the ORM.

Upvotes: 1

Related Questions