2017-07-17 46 views
0

私はUsersテーブルとGroupsテーブルを持っています。私は単一のユーザーを取得するときに、そのユーザーが属するすべてのグループのリストを取得したいと思います。 GroupUsersという名前のジョインテーブルを作成しましたが、それにはuserIdgroupIdがあります。これは、ユーザーがグループに所属していることを知る方法です。ユーザーが属しているグループのリストをincludefindに取得しようとすると、ユーザーがいろいろなグループに属していれば最初の一致が返されます。これをどうすれば解決できますか?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

答えて

0

私の団体に、私がしたことが表示されますまた返された、私はそれを削除して:

include: [{ 
    model: models.Groups, 
    as: 'groups', 
    attributes: ['id', 'name'], 
    through: { attributes: [] } 
    }] 

attributesが空の配列に設定されているthroughキーに注意してください。

関連する問題