簡體   English   中英

Sequelize 查詢在多對多關系中顯示附加數據

[英]Sequelize query shows additional data in Many to Many relationship

我有這個設置,用戶和主題之間的多對多關系:

User.belongsToMany(Topic, {through: "UserTopics", timestamps: false});
Topic.belongsToMany(User, {through: "UserTopics", timestamps: false});

我嘗試獲取所有用戶及其主題,這個查詢做得很好:

User.findAll({
    attributes: { exclude: ["password"] },
    include: [
      { model: Topic, attributes: ['id', 'name',] }
    ]
  })

這是它的輸出:

[
    {
        "id": 1,
        "firstName": "John",
        "lastName": "Doe",
        "CNP": "123",
        "email": "john@gmail.com",
        "validated": false,
        "createdAt": "2021-02-15T21:46:52.000Z",
        "updatedAt": "2021-02-15T21:46:52.000Z",
        "topics": [
            {
                "id": 1,
                "name": "crypto",
                "UserTopics": {
                    "userId": 1,
                    "topicId": 1
                }
            },
         ...
     },
     ...
]

但是我遇到的問題是我無法弄清楚為什么會發生這種情況是 UserTopics 屬性會為用戶擁有的每個主題顯示。

我該如何擺脫它?

閱讀此https://sequelize.org/master/manual/advanced-many-to-many.html

如果要從結果中排除關聯字段:

User.findAll({
    attributes: { exclude: ["password"] },
    include: [
      { model: Topic, attributes: ['id', 'name',] }
    ],
    through: {
      attributes: []
    }
})

感謝fatur指出頁面。 這樣做的實際方法與他寫的有點不同。 “through”屬性必須在數組 object 內,如下所示:

User.findAll({
    attributes: { exclude: ["password"] },
    include: [
        {
            model: Topic,
            attributes: ["id", "name"],
            through: {
                attributes: []
            }
        }
    ]
})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM