【问题标题】:Sequelize-typescript include on Many to Many only includes one of many resultsSequelize-typescript include on Many to Many 只包括许多结果之一
【发布时间】:2019-01-26 08:01:14
【问题描述】:

我正在尝试在用户和可能描述它们的标签之间创建多对多关系,并在获取用户时包含用户标签数组。问题是用户对象中只包含了许多关联标签中的一个。

我认为我的代码存在一个简单的问题,但对我来说,它看起来就像我正在关注文档上的示例。具有一对多或一对一关联的所有其他包含都可以正常工作。

tag.model.ts

@DefaultScope({ attributes: ['text', 'color'] })
@Table({
    paranoid: true,
    timestamps: true,
    freezeTableName: true,
    tableName: 'tags',
})
export default class Tag extends Model<Tag> {
    // ...
    @BelongsToMany(() => User, () => UserTag)
    users!: User[];
}

user.model.ts

@Table({
    paranoid: true,
    timestamps: true,
    freezeTableName: true,
    tableName: 'users'
})
export default class User extends Model<User> {
    // ...
    @BelongsToMany(() => Tag, () => UserTag)
    tags!: Tag[];
}

usertag.model.ts

@Table({
    freezeTableName: true,
    tableName: 'user_tags'
})
export default class UserTag extends Model<UserTag> {
    @ForeignKey(() => User)
    @Column
    user_id!: number;

    @ForeignKey(() => Tag)
    @Column
    tag_id!: number;
}

sequelize.config.ts

// ...
User.addScope('public', {
    include: [
        // ...
        { model: Tag, as: 'tags', through: { attributes: [] } },
    ]
} as IFindOptions<User>);

打电话时

User.scope('public').findByPk( ... )

返回的对象例如只包含第一个Tag

"tags": [
            {
                "text": "Cool Guy",
                "color": "#002B36"
            }
        ],

当数据库中存在更多标签时

1, Cool Guy, #002B36
2, New Tag, #00FF00 ...

以及更多用户标签(user_id、tag_id)

1, 1
1, 2 ...

【问题讨论】:

    标签: node.js sequelize.js sequelize-typescript


    【解决方案1】:

    发布此问题时,我简化了代码以删除大部分模型列,这些列显然与问题无关,但我也忽略了标签具有将其属性限制为“名称”和“的 DefaultScope”颜色'。问题是这不包括主键,在这种情况下是 'id'。

    只需将“id”添加到默认范围即可解决问题。哎呀。

    【讨论】:

      猜你喜欢
      • 2020-07-01
      • 1970-01-01
      • 2016-11-05
      • 1970-01-01
      • 1970-01-01
      • 2016-09-05
      • 1970-01-01
      • 1970-01-01
      • 2019-04-20
      相关资源
      最近更新 更多