我在Node.JS应用程序中使用PostgreSQL,并且我使用SequelizeJS作为ORM。我有以下查询:
我们说我有两种模式:
User(name,email)
Category(name,createdBy)
Category.createdBy
是引用User.id
的外键
这两个表有多对多的关系:
Category.belongsToMany(models.User, {through: 'UserCategory'});
User.belongsToMany(models.Category, {through: 'UserCategory'});
如果某个类别与用户相关联,则UserCategory表上将存在一个映射。否则就赢了。
如何"选择"将找到所有类别的实例,这些类别是由用户X创建的或与用户X相关联的,即(categories associated to user X) + (categories created by user X)
?
答案 0 :(得分:0)
答案 1 :(得分:0)
默认情况下,Sequelize会将get / set / add / remove方法添加到模型实例中。
// All categories associated to userId
User.findById(userId).getCategories()
// All categories create by userId
Category.findAll({
where: {
createdBy: userId
}
})
答案 2 :(得分:-1)
试试这个:
Category.belongsToMany(models.User, {through: 'CreateCategory'});
User.belongsToMany(models.Category, {through: 'CreateCategory','foreignKey':'createdBy' });
这将允许您与存储createdBy
和Category
的{{1}}字段的其他表定义其他关系