Associations: how to get associated object rather then fk id

37 views
Skip to first unread message

mill

unread,
Oct 3, 2016, 10:40:34 AM10/3/16
to Sequelize
Hi all

Suppose to have this situation:

DB SIDE:

I have two tables USER --> USER_TYPE where Cardinality is 1-1 / 1-N An USER can have one USER_TYPE.
So,USER table have a FOREIGN_KEY linked on it USER_TYPE_ID column.


SEQUELIZE SIDE:


var User = sequelize.define('User',
{
userId:
{
field: 'USER_ID',
type: DataTypes.INTEGER ,
primaryKey: true,
autoIncrement: true
},
......
......
},
{
timestamps: false,
tableName: 'users'
}
);

User.belongsTo(UserType,{ foreignKey: 'USER_TYPE_ID'});



var UserType = sequelize.define('UserType',
{
userTypeId:
{
field: 'USER_TYPE_ID',
type: DataTypes.INTEGER ,
primaryKey: true,
autoIncrement: true
},

....
....
},
{
timestamps: false,
tableName: 'user_types'
}
);



I Try to retrieve User with it linked UserType in this way:

return User.findById(id,{ include: [ UserType] })
.then(function(result)
{
var resultAsPlain = result.get({plain: true});
console.log(resultAsPlain);
})
.catch(function(err)
{
console.log(err);
return err;
});


This is the output of console:

{
    userId
: 9,
    name
: 'Jhon',
    surname
: 'Locke',
   
USER_TYPE_ID: 2,
   
UserType:
   
{
        userTypeId
: 2,
        description
: 'Admin',
        code
: 'ADM'
   
}
}

Is there a way to get ONLY the associated OBJECT UserType,without the USER_TYPE_ID field (backgrounded in RED) ?

Something like this:

{
    userId
: 9,
    name
: 'Jhon',
    surname
: 'Locke',
   
UserType:
   
{
        userTypeId
: 2,
        description
: 'Admin',
        code
: 'ADM'
   
}
}

Thank you!


Mark Lester

unread,
Oct 25, 2016, 5:36:29 AM10/25/16
to Sequelize
well just leave it off the include. if you need only a specific type you can go

return User.findById(id,{ 
  where:{
    USER_TYPE_ID:idIwant
  }
})  


Ah, not sure what the foreign key in User is going to look like, I think it might be UserTypeId if you didnt specify an 'as' fieldname in the definition, go look in User table that sequelzie has made and work out what the join key is that sequelize has made.
Reply all
Reply to author
Forward
0 new messages