Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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$/});
like image 386
trentjones21 Avatar asked Aug 17 '15 17:08

trentjones21


1 Answers

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.

like image 104
trentjones21 Avatar answered Oct 06 '22 00:10

trentjones21