trentjones21
trentjones21

Reputation: 571

Sequelize belongsToMany not creating new table

Using sequelize, I expect this line:

m.User.belongsToMany(m.Company, {through: 'UserCompany'});

to generate a new table in my database called 'user_company' that would link the 'user' table and the 'company' table together. However, it isn't doing that. Am I misunderstanding the documentation when it says

This will create a new model called UserProject with with the equivalent foreign keys ProjectId and UserId. Whether the attributes are camelcase or not depends on the two models joined by the table (in this case User and Project).

or am I doing something wrong?

Here are the relations I am setting up

m.Company.hasMany(m.User);
m.User.belongsToMany(m.Company, {
    through: m.UserCompany
});

m.User.sync({force: true, match: /_test$/});
m.Company.sync({force: true, match: /_test$/});
m.UserCompany.sync({force: true, match: /_test$/});

Upvotes: 6

Views: 2730

Answers (1)

trentjones21
trentjones21

Reputation: 571

Looks like I needed to create the UserCompany model manually. So, UserCompany.js looks like:

module.exports = function(sequelize, DataTypes) {

return sequelize.define('UserCompany', {

}, {
    freezeTableName: true,
    paranoid: true
});

}

Then the belongsToMany automatically adds the correct columns to the table.

Upvotes: 2

Related Questions