belongsto with foreign key on legacy table

20 views
Skip to first unread message

zoell2

unread,
Aug 4, 2016, 7:26:51 AM8/4/16
to Sequelize
Hi,

I have to work on a legacy database and there's a simple association that I could not figure out.

So I have a pet_list table with the following columns:
id, something1, something2, user(INT)

Column user has a foreign key (fk_pet_user) to the User table's id column. So every user has one or more pets.

This is my model definition for the pet_list (Pet.js):

Pet.js:
module.exports = {
    attributes
: {
        something1
: {
            type
: Sequelize.INTEGER
       
},
        something2
: {
            type
: Sequelize.STRING
       
}
   
},
    associations
: function () {
       
Pet.user = Pet.belongsTo(User, {
            targetKey
: 'id',
            foreignKey
: 'fk_pet_user'
       
});
   
},
    options
: {
        freezeTableName
: true,
        tableName
: 'pet_list'
   
},
};

Also, the user table has: id, name, anything.

User.js definition:
module.exports = {
  attributes
: {
    name
: {
      type
: Sequelize.STRING
   
},
    anything
: {
      type
: Sequelize.STRING
   
}
 
},
  options
: {
    freezeTableName
: true,
    tableName
: 'user'
 
},
}

And when I try to insert a record to pet list:
sequelize.transaction(function (t) {
 
return Pet.create({something1: 123, something2: "asdf", user: 15}, {transaction: t});
}).then(function (result) {
 
// handle results...
}).catch(function (err) {
 
// error...
});

So the user field contains the ID of the user it belongs to, it just adds a record but the user field is empty.

Is there anything I am missing?

Thank you,
Zoltan
Reply all
Reply to author
Forward
0 new messages