Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'
}
like image 227
Robin Claes Avatar asked Feb 25 '26 16:02

Robin Claes


1 Answers

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.

like image 93
PhilippeAuriach Avatar answered Feb 28 '26 04:02

PhilippeAuriach



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!