私はUsers
テーブルとGroups
テーブルを持っています。私は単一のユーザーを取得するときに、そのユーザーが属するすべてのグループのリストを取得したいと思います。 GroupUsers
という名前のジョインテーブルを作成しましたが、それにはuserId
とgroupId
があります。これは、ユーザーがグループに所属していることを知る方法です。ユーザーが属しているグループのリストをinclude
のfind
に取得しようとすると、ユーザーがいろいろなグループに属していれば最初の一致が返されます。これをどうすれば解決できますか?sequelize includeは1つの結果しか返しません
Users controller
return models.Users
.find({
include: [{
model: models.Groups,
as: 'groups',
limit: null,
required: false
}],
where: { username }
})
Returns this:
{
"id": 1,
"username": "John",
"phone": "xxxxxxxx",
"email": "[email protected]",
"createdAt": "2017-07-16T20:14:04.744Z",
"updatedAt": "2017-07-16T20:14:04.744Z",
"groups": [
{
"id": 1,
"name": "Test Group",
"type": "Public",
"createdAt": "2017-07-16T20:13:18.392Z",
"updatedAt": "2017-07-16T20:13:18.392Z",
"GroupUsers": {
"userId": 1,
"groupId": 1,
"last_seen": null,
"createdAt": "2017-07-16T20:14:27.903Z",
"updatedAt": "2017-07-16T20:14:27.903Z"
}
}
]
}
Instead of this:
{
"id": 1,
"username": "John",
"phone": "xxxxxxxx",
"email": "[email protected]",
"createdAt": "2017-07-16T20:14:04.744Z",
"updatedAt": "2017-07-16T20:14:04.744Z",
"groups": [
{
"id": 1,
"name": "Test Group",
"type": "Public",
"createdAt": "2017-07-16T20:13:18.392Z",
"updatedAt": "2017-07-16T20:13:18.392Z",
"GroupUsers": {
"userId": 1,
"groupId": 1,
"last_seen": null,
"createdAt": "2017-07-16T20:14:27.903Z",
"updatedAt": "2017-07-16T20:14:27.903Z"
}
},
{
"id": 2,
"name": "Test Group 2",
"type": "Public",
"createdAt": "2017-07-16T20:13:18.392Z",
"updatedAt": "2017-07-16T20:13:18.392Z",
"GroupUsers": {
"userId": 1,
"groupId": 2,
"last_seen": null,
"createdAt": "2017-07-16T20:14:27.903Z",
"updatedAt": "2017-07-16T20:14:27.903Z"
}
}
]
}
私はちょうどどこかわからない、私はどこか間違って何かをやっていると確信している、その同じことまた、rのjoinテーブルを含むsequelizeの原因かもしれませんesult:
Users.belongsToMany(models.Groups, {
through: 'GroupUsers',
as: 'groups',
foreignKey: 'groupId'
});
の代わりに::
Users.belongsToMany(models.Groups, {
through: 'GroupUsers',
as: 'groups',
foreignKey: 'userId'
});
foreignKey
属性
されGroupUsers
オブジェクトのように注意をGroupUsers