Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get join data result without prefix table name in Sequelize ORM

Tags:

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": "[email protected]",
    "username": "test",
    "status": "Active",
    "role.role_id": 1,
    "role.role_name": "Admin"
}]

but I need this result:

[{
    "id": 36,                
    "email": "[email protected]",
    "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'

like image 419
Mukesh Singh Thakur Avatar asked May 03 '18 06:05

Mukesh Singh Thakur


2 Answers

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

like image 88
Mayur Avatar answered Oct 12 '22 13:10

Mayur


This should work

A is a table that is associated to B using a column called bId so B has a primary key of Id which is associates to a bid column in A table that is shown in the standard result set as b.id but we want these two column to be called as Id & Name

A.belongsTo(B);
        return await A.findAll({
            attributes: [
                [Sequelize.col('b.id'), 'Id'],
                [Sequelize.col('b.name'), 'Name']
            ],
            raw: true,
            where: { /*Some condition*/ },
            include: {
                model: B,
                attributes: [],
                required: true
            },
        });
like image 38
sishanov Avatar answered Oct 12 '22 13:10

sishanov