我正在使用sequelize-typescript库的sequelize,并尝试实现以下关系:
Team.ts
@Scopes({
withPlayers: {
include: [{model: () => User}]
}
})
@Table
export default class Team extends Model<Team> {
@AllowNull(false)
@Column
name: string;
@BelongsToMany(() => User, () => TeamPlayer)
players: User[];
}
User.ts
@Scopes({
withTeams: {
include: [{model: () => Team, include: [ () => User ]}]
}
})
@Table
export default class User extends Model<User> {
@AllowNull(false)
@Column
firstName: string;
@AllowNull(false)
@Column
lastName: string;
@BelongsToMany(() => Team, () => TeamPlayer)
teams: Team[];
}
TeamPlayer.ts
@DefaultScope({
include: [() => Team, () => User],
attributes: ['number']
})
@Table
export default class TeamPlayer extends Model<TeamPlayer> {
@ForeignKey(() => User)
@Column
userId: number;
@ForeignKey(() => Team)
@Column
teamId: number;
@Unique
@Column
number: number;
}
现在查询播放器时,您将获得包含以下数据的对象:
{
"id": 1,
"name": "Doe's Team",
"players": [
{
"id": 1,
"firstName": "John",
"lastName": "Doe",
"TeamPlayer": {
"userId": 1,
"teamId": 1,
"number": 32
}
}]
}
现在有几件我无法完成的事情......
1)我想将TeamPlayer
重命名为“会员资格”;但不是通过更改类的名称
2)TeamPlayer
的内容不应该包含id,但我希望它包含团队的数据,例如:
{
"firstName": "John",
"lastName": "Doe"
"membership": {
"number": 32
}
在上面的课程中,我尝试将范围设置为TeamPlayer
类,仅在number
包含内包含TeamMember
,但没有效果。
我曾经让TeamPlayer
类拥有team
和player
的直接成员资格,但该解决方案为id
类添加了多余的TeamPlayer
,并且也没有阻止团队中的重复成员资格。我确实可以手动(=在代码中)防止在这些情况下重复,但这感觉不太优雅。
答案 0 :(得分:1)
我最后通过添加从TeamPlayer
到User
和Team
的一对多关系来解决这个问题,并且还想出了制作teamId
+的方法通过userId
添加另外两个字段,@ForeignKey
对唯一,如下所示:
<强> TeamPlayer.ts 强>
@Table
export default class TeamPlayer extends Model<TeamPlayer> {
@BelongsTo(() => Team)
team: Team;
@ForeignKey(() => Team)
@PrimaryKey
@Column
teamId: number;
@BelongsTo(() => User)
user: User;
@ForeignKey(() => User)
@PrimaryKey
@Column
userId: number;
@Column
number: number;
}
<强> User.ts 强>
@Table
export default class User extends Model<User> {
@AllowNull(false)
@Column
firstName: string;
@AllowNull(false)
@Column
lastName: string;
@HasMany(() => TeamPlayer)
teams: TeamPlayer[];
}
<强> Team.ts 强>
export default class Team extends Model<Team> {
@AllowNull(false)
@Column
name: string;
@HasMany(() => TeamPlayer)
players: TeamPlayer[];
}
此解决方案允许我通过范围控制包含的查询属性,并为我提供适当的对象输出。