Sunny
Sunny

Reputation: 187

Sequelize Include Model But Without Tablename

I'm newbie for Sequelize

I have a problem with "Nested Eager Loading"

I have 2 Table with 1-to-many relationship

  1. Comment Table

  2. User Table

I use this code for the query

Comment.findAll({
   include: [User]
})

I got

{
    id: 1,
    comment: "test",
    user: {
       id: 3,
       name: "someone"
    }
}

But I expected result like this

{
    id: 1,
    comment: "test",
    user_id: 3,
    user_name: "someone"
}

I read several stackoverflow post it has a solution but work for version 3.3

Comment.findAll({
   attributes: ['id', 'name', ['user.id','user_id'], ['user.name','user_name']]
   include: [{ model: User, attributes:[], nested: false, required: true }]
})
Comment.findAll({
   attributes: ['id', 'name', [Sequelize.col('user.id'),'user_id'], [Sequelize.col('user.name'),'user_name']]
   include: [{ model: User, attributes:[], nested: false, required: true }]
})

but it's not work for me.

now I use sequelize 5.5.1 how can I implement it.

Can someone help me, please?

Upvotes: 2

Views: 1354

Answers (1)

Prabhjot Singh Kainth
Prabhjot Singh Kainth

Reputation: 1861

You can use this code to get the desired output:

Since Sequelize is promised based , it is recommend to use then and catch.

Comment.findAll({
   include: [User]
}).then(result=>
{
  let obj=
{
    id: result.item,
    comment: result.comment,
    user_id: result.user.id,
    user_name: result.user.name
};
console.log(JSON.stringify(obj));

}).catch(err=>
{
console.log(err);
});

Upvotes: 1

Related Questions