作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
如果您有以下实体:用户、角色、组织。
您希望设置关系,以便每个用户都有一个组织角色。
简单地说,每个用户可以属于多个组织,并且用户在每个组织中都有特定的角色。
您将如何使用 Sequelize 对此进行建模?
我尝试创建一个名为 organization_users 的连接表,然后在该表中添加一个 organizationUsers.belongsTo(role);
从我读过 Sequelize 不支持连接表上的关联,因此该解决方案不起作用。
问候,
埃米尔
最佳答案
Sequelize 确实支持连接表上的关联。您应该查看“通过”选项 here >
例子 :
const Asso_Organization_User = sequelize.define('Asso_Organization_User', {
id: DataTypes.STRING,
userId: DataTypes.STRING,
organizationId: DataTypes.STRING
});
User.Organizations = User.belongsToMany(Organization, {
through: Asso_Organization_User,
foreignKey: 'userId',
otherKey: 'organizationId',
as: 'organizations'
})
const Asso_Organization_User = sequelize.define('Asso_Organization_User', {
id: DataTypes.STRING,
userId: DataTypes.STRING,
organizationId: DataTypes.STRING
});
User.Organizations = User.belongsToMany(Organization, {
through: Asso_Organization_User,
foreignKey: 'userId',
otherKey: 'organizationId',
as: 'organizations'
})
User: id
Role: id, userId, organizationId
Organizations: id
Asso_Organization_User: id, userId, organizationId
User.Organizations = User.belongsToMany(Organization, {
through: Asso_Organization_User
})
Organization.Roles = Organization.haMany(Role, {
foreignKey: 'organizationId'
})
User.findAll({
include: [ {
model: Organization,
include: {
model: Role
}
} ]
where: {
'role.userId': Sequelize.col("User.id")
}
});
关于sequelize.js - Sequelize : How to make relationship between 3 tables,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51533572/
我是一名优秀的程序员,十分优秀!