我有一个用户:
@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!
我做错了什么?
正确方法:
@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'
}]
})