Sequelize User M2M Group - 그룹에 속한 사용자 찾기
프로젝트에서는 사용자 및 그룹이 있고 사용자는 여러 개의 그룹을 가질 수 있습니다.특정 그룹에 속한 사용자를 기준으로 사용자 목록을 필터링하는 데 문제가 있습니다.
제 설정은 이렇습니다.
사용자 모델
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 Through Table :: 사용자 그룹
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',
});
내 db 사용자는 다음과 같습니다(간단히).
User1.groups = [1,2,3]
User2.groups = [1,3]
User3.groups = [2,3]
검색 휴식 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를 가져온 다음 다음 다음 작업을 수행해야 하는 것과 같습니다.
query.where = {id: {[Op.in]: userIdsArray}}
언급URL : https://stackoverflow.com/questions/52636776/sequelize-user-m2m-group-find-users-that-are-in-groups
'programing' 카테고리의 다른 글
| 동적 매개변수를 사용한 Oracle Lag 함수 (0) | 2023.09.28 |
|---|---|
| jQuery를 사용하여 원소의 위쪽에서 px로 수직 거리를 찾는 방법 (0) | 2023.09.28 |
| CSS에서 if/else 조건을 사용할 수 있습니까? (0) | 2023.09.23 |
| 스파크 데이터 프레임을 만듭니다.유형에 대한 스키마를 유추할 수 없습니다. (0) | 2023.09.23 |
| "inti = 1;왜 (i > = 60 * 60 * 1000 / 1 * 1000)"가 참입니까? (0) | 2023.09.23 |