我想用feather-sequelize在两个模型之间添加多对多关系,并在连接表中添加额外的属性。sequelize的文档对此很清楚:我必须创建一个新模型,我喜欢这样使用
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 })但是,当我在feather应用程序中定义一个新模型时,它不是在数据库中创建的,因此我的关系不起作用
发布于 2019-01-25 22:32:16
只是为了检查我是否理解正确:你想要有一个链接表(例如,user_projects),并将UserProjects模型映射到它,从而在User和Project模型之间创建多对多关系?
您可以使用hasMany和belongsTo函数,而不是belongsToMany函数,如下所示:
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'
});并且您需要将链接表中的user_id和project_id列定义为外键。
然后,您可以在链接表中添加任何其他属性(status或其他任何属性,这都无关紧要)
https://stackoverflow.com/questions/54118713
复制相似问题