3
votes

I've been having some problems with Sequelize and foreign keys, they're not created in the database when I sync

this is my Users.js

module.exports = function(sequelize, DataTypes) {
    var Users = sequelize.define('users', {
      name: DataTypes.STRING      
    }, {
        classMethods: {
            associate: function(models) {
                Users.belongsTo(models.group);
            }
        }
    });
    return Users;
}

and this is my Groups.js

module.exports = function(sequelize, DataTypes) {
  var Group = sequelize.define("group", {
    nome: DataTypes.STRING
  });
  return Group;
};

Already tried this:

var Group = require('./Group');
module.exports = function(sequelize, DataTypes) {
    var Users = sequelize.define('users', {
      name: DataTypes.STRING    
    });
    Users.hasOne(Group);
    return Users;
}

but no result.

Obs: I have models.sequelize.sync({ force: true }) on project start

what am I missing?

Thanks!

2

2 Answers

4
votes

Similar issue: classMethod removed https://stackoverflow.com/a/45473628/6811324

User.hasOne(Group, {foreignKey: 'userId'}) // userId foreignKey on Group

Users.hasOne(Group); // UserId foreignKey on Group

    or

Users.belongsTo(models.Group, {foreignKey: 'groupId'}); // groupId to User
1
votes

What version of sequelize are you using? I was using version "sequelize": "^4.31.2" with mysql2 package and faced same problem. I switched back to version "sequelize": "^2.0.0" with mysql package and problem solved.

I think manually defining foreign key is better way to go.