在同一张表上序列化多对多

问题描述 投票:0回答:1

我有一个用户:

@Table({
    underscored: true,
})
export default class User extends Model {
    @PrimaryKey
    @Column
    id: string;

    @AllowNull(false)
    @Column
    name: string;

    @AllowNull(false)
    @Column
    username: string;

    @AllowNull(false)
    @Column
    password: string;

    @BelongsToMany(() => User, () => Follow, 'followeeId')
    followers: Follow[]

    @BelongsToMany(() => User, () => Follow, 'followerId')
    following: Follow[]
}

和下表:

@Table({
    underscored: true,
})
export default class Follow extends Model {
    @ForeignKey(() => User)
    @Column
    followerId: string;

    @ForeignKey(() => User)
    @Column
    followeeId: string;
}

现在我尝试加载用户记录及其所有关注者和关注者:

const follows = await User.findByPk(req.userId, {
    include: [Follow, Follow]
})

但是从续集得到这个:

EagerLoadingError [SequelizeEagerLoadingError]: Follow is not associated to User!

我做错了什么?

sequelize.js many-to-many sequelize-typescript
1个回答
0
投票

正确方法:

@BelongsToMany(() => User, () => Follow, 'followerId')
followers: User[]

@BelongsToMany(() => User, () => Follow, 'followeeId')
following: User[]

然后

const user = await User.findByPk(req.userId, {
    include: [{
        model: User,
        as: 'followers'
    },{
        model: User,
        as: 'following'
    }]
})
© www.soinside.com 2019 - 2024. All rights reserved.