在我的项目中,我有用户和组,一个用户可以有多个组。我无法根据特定组中的用户来过滤用户列表。
这是我的设置:
用户模型
module.exports = (sequelize) => {
const model = sequelize.define('users',
{
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
field: 'uID',
},
username: {
type: Sequelize.STRING, allowNull: false, unique: true, field: 'uEmail',
},
}, {
timestamps: false,
tableName: 'Users',
});
model.modelName = 'users';
return model;
};
组模型
module.exports = (sequelize) => {
const model = sequelize.define('groups', {
id: {
type: Sequelize.INTEGER,
autoIncrement: true,
primaryKey: true,
field: 'gID',
},
name: { type: Sequelize.STRING, allowNull: false, field: 'gName' },
description: { type: Sequelize.STRING, allowNull: false, field: 'gDescription' },
}, {
timestamps: false,
tableName: 'Groups',
});
model.modelName = 'groups';
return model;
};
M2M通过表::用户组
module.exports = (sequelize) => {
const model = sequelize.define('usergroups', {
}, {
timestamps: false,
tableName: 'UserGroups',
});
model.modelName = 'usergroups';
return model;
};
协会
User.belongsToMany(Group, {
through: UserGroup,
as: 'groups',
foreignKey: 'uID',
});
Group.belongsToMany(User, {
through: UserGroup,
as: 'users',
foreignKey: 'gID',
});
我的数据库用户看起来像这样(简写):
User1.groups = [1,2,3]
User2.groups = [1,3]
User3.groups = [2,3]
我正在构建Search Rest API:GET /users?groups[]=1&groups[]=2
在构建查询时,我尝试根据使用以下格式传递的组进行过滤:
let query = {};
query.include = [
{
model: Group,
as: 'groups',
where: {id: {[Op.in]: filter.groups}},
attributes: ['id', 'name'],
},
];
const result = yield User.findAndCountAll(query);
或尝试使用through
(与required: true
或required: false
一起使用):
let query = {};
query.include = [
{
model: Group,
as: 'groups',
through: { where: {'gID': {[Op.in]: filter.groups}}, required: true},
attributes: ['id', 'name'],
},
];
const result = yield User.findAndCountAll(query);
这是可行的,除了返回的对象相关组的缩写。如果我通过了此过滤器:
GET /users?groups[]=1
正确的用户会返回响应,但是会过滤与这些用户相关的组:
[
{
"id": 1,
"username": "user1@site.com",
"groups": [
{
"id": 1,
"name": "My Group",
"usergroups": {
"uID": 1,
"gID": 1
}
}
]
},
{
"id": 2,
"username": "user2@site.com",
"groups": [
{
"id": 1,
"name": "My Group",
"usergroups": {
"uID": 2,
"gID": 1
}
}
]
}
]
但是User1的组2和3,User2的组2在哪里?
几乎就像我需要获取特定组中的所有用户ID(通过Group服务类)然后执行:
query.where = {id: {[Op.in]: userIdsArray}}