I am trying to establish a belongsToMany relationship between two models, User and Company.
I think I have done everything right, but the funny thing is that the api shows me the results relationships when I query User, but when I try to query Company, it gives me the following error:
User is not associated to Company!
These are my two models and the relations:
user.model.js
export default (sequelize, DataTypes) => {
const User = sequelize.define('User',
{
id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING, allowNull: false },
password: { type: DataTypes.STRING },
email: { type: DataTypes.STRING, unique: true }
},
{
tableName: 'users',
paranoid: true,
timestamps: true,
underscored: true
});
User.associate = models => {
User.belongsToMany(models.Company, {
through: 'CompanyUsers',
as: 'companies',
foreignKey: 'user_id'
});
};
return User;
};
company.model.js
export default (sequelize, DataTypes) => {
const Company = sequelize.define('Company',
{
id: { type: DataTypes.INTEGER, allowNull: false, primaryKey: true, autoIncrement: true },
name: { type: DataTypes.STRING, allowNull: false },
code: { type: DataTypes.STRING, allowNull: false },
disabled: { type: DataTypes.BOOLEAN, defaultValue: false },
},
{
tableName: 'companies',
paranoid: true,
timestamps: true,
underscored: true
});
Company.associate = models => {
Company.belongsToMany(models.User, {
through: 'CompanyUsers',
as: 'users',
foreignKey: 'company_id'
});
};
return Company;
};
Any idea?
Thanks!!