【发布时间】: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