可以定义两个外键作为模型的复合主键吗?
一个用户只能是一个家庭的成员,一个家庭可以有多个成员,family-members表需要用户和家庭的引用
const User = sequelize.define(
'User',
{
id: { type: dataTypes.INTEGER.UNSIGNED, autoIncrement: true, primaryKey: true },
name: { type: dataTypes.STRING(30) },
email: { type: dataTypes.STRING(30) }
...
},
{
classMethods: {
associate(models) {
User.hasOne(models.FamilyMember, {
foreignKey: 'user_id'
}
}
}
}
)
const Family = sequelize.define(
'Family',
{
name: { type: dataTypes.STRING(30) }
},
{
classMethods: {
associate(models) {
Family.hasMany(models.FamilyMember, {
foreignKey: 'family_id'
}
}
}
}
)
const FamilyMember = sequelize.define(
'FamilyMember',
{
name: { type: dataTypes.STRING(30) },
/*
family_id and user_id will be here after associations but I wanted them to be a composite primaryKey
*/
}
)
最佳答案
事实上,我几乎从文档中得到了解决方案:
User = sequelize.define('user', {});
Project = sequelize.define('project', {});
UserProjects = sequelize.define('userProjects', {
status: DataTypes.STRING
});
User.belongsToMany(Project, { through: UserProjects });
Project.belongsToMany(User, { through: UserProjects });
By default the code above will add projectId and userId to the UserProjects table, and remove any previously defined primary key attribute - the table will be uniquely identified by the combination of the keys of the two tables, and there is no reason to have other PK columns.
关于node.js - Sequelize,外键作为复合主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36883437/