I want to add a many to many relationship between two model with feather-sequelize and in the join table, I want to add additionnal attribut. The documentation of sequelize is clear about it: I have to create a new model an use I like this
const User = sequelize.define('user', {})
const Project = sequelize.define('project', {})
const UserProjects = sequelize.define('userProjects', {
status: DataTypes.STRING
})
User.belongsToMany(Project, { through: UserProjects })
Project.belongsToMany(User, { through: UserProjects })
But when I define a new model in my feather application, it is not created in the database so my relation is not working
Just to check if I understand correctly: you want to have a link table (eg. user_projects
), and map the UserProjects
model to it, thus creating a many-to-many relationship between User
and Project
models?
You can use the hasMany
and belongsTo
functions, instead of belongsToMany
like:
User.hasMany(UserProjects, {
as: 'UserProjects',
foreignKey: 'user_id' // this is what you're missing
});
Project.hasMany(UserProjects, {
as: 'UserProjects',
foreignKey: 'project_id' // this is what you're missing
});
UserProjects.belongsTo(User, {
as: 'Users',
foreignKey: 'user_id'
});
UserProjects.belongsTo(Projects, {
as: 'Projects',
foreignKey: 'project_id'
});
And you need to define the user_id
and project_id
columns in your link table, as Foreign Keys.
Then you can add whatever other attributes you want in your link table (status
or whatever else, it doesn't matter)