1
votes

A very straightforward question. Am using nodejs 5.6, express 4 and sequelize 4. In the program, I have a user object which belongs to company object.

var User = sequelize.define('user', {
    username: {
        type: Sequelize.STRING
    },
    password: {
        type: Sequelize.STRING
    }
});

const Company= sequelize.define('companny', {
    record: {
        type: Sequelize.JSON
    }
});

Company.associate = function(models) {
    console.log(models)
    Company.hasMany(models.User, {
        foreignKey: {
            // name: 'user',
            allowNull: true
        }
    })
}

when running the program, the database is created with user and company table, but there is no foreign key in eight user or company. And the console outputs nothing. Any suggestion?

2

2 Answers

1
votes

Finally, the index.js file here answers my question.

0
votes

I would normally use this method to create my models:

// User model
export default (sequelize, DataTypes) => {
  const User = sequelize.define('User', {
    email: {
      allowNull: false,
      type: DataTypes.STRING,
      unique: true
    },
    password: {
      allowNull: false,
      type: DataTypes.STRING,
    }
  });

  return User;
};

// Company model
export default (sequelize, DataTypes) => {
  const Company = sequelize.define('Company', {
    record: {
        type: DataTypes.JSON
    }
  });

  Company.associate = (models) => {
    console.log(models)
    Company.hasMany(models.User, {
        foreignKey: 'userId'
    })
  }

  return Company;
};