在我的社交应用程序中,用户可能想将用户列入黑名单(就像很多社交应用程序一样)。
用户 (但已列入黑名单的用户) ManyToOne 黑名单
用户许多对黑名单
用户:
@Entity()
@Unique(["username"])
export class User
{
@PrimaryGeneratedColumn()
id: number;
@Column()
@Length(4, 20)
username: string;
@Column()
@Length(4, 100)
password: string;
@Column()
@IsNotEmpty()
role: string;
@Column()
@CreateDateColumn()
createdAt: Date;
@OneToMany(type => Blacklist, blacklist => blacklist.user)
blacklist: Blacklist[];
@ManyToMany(type => Blacklist)
@JoinTable({
"name": "user_blacklist"
})
blacklists:Blacklist[]
@Column()
@UpdateDateColumn()
updatedAt: Date;
hashPassword() {
this.password = bcrypt.hashSync(this.password);
}
checkIfUnencryptedPasswordIsValid(unencryptedPassword: string) {
return bcrypt.compareSync(unencryptedPassword, this.password);
}
}
黑名单:
@Entity()
export class Blacklist {
@PrimaryGeneratedColumn()
id: number;
@ManyToOne(type => User, user => user.blacklist)
user: User;
}
这是我在 post('user / blacklist')
上调用的方法static addBlacklist = async (req: Request, res: Response) => {
const { id, blacklisted_id } = req.body;
const blacklistRepository = getRepository(Blacklist);
const userRepository = getRepository(User);
let user: User
let blacklistedUser: User;
try {
user = await userRepository.findOneOrFail(id);
blacklistedUser = await userRepository.findOneOrFail(blacklisted_id);
} catch(error) {
res.status(404).send({error: error});
}
let blacklist = new Blacklist();
blacklist.user = blacklistedUser;
// user.blacklists.push(blacklist);
try {
await blacklistRepository.save(blacklist);
await userRepository.save(user);
res.status(201).send('success blacklisted');
} catch (error) {
res.status(404).send({error: error});
}
}
它适用于黑名单,我有一个包含黑名单用户ID的新黑名单。但我无法添加user_blacklist(希望我很清楚)
所以我尝试添加:
user.blacklists.push(blacklist); // see above comment
但我知道
(节点:40495)UnhandledPromiseRejectionWarning:TypeError:无法读取未定义的属性“ push”
blacklist // works
+------------+--------------+
| id | userId |
+------------+--------------+
| 1 | 1 |
+------------+--------------+
user_blacklist // not works cause of cannot push and save
+------------+--------------+
| userId | blacklistId |
+------------+--------------+
| Empty |
+------------+--------------+
blacklist
+------------+--------------+
| id | userId |
+------------+--------------+
| 1 | 2 |
+------------+--------------+
user_blacklist
+------------+--------------+
| userId | blacklistId |
+------------+--------------+
| 1 | 1 |
+------------+--------------+
感谢帮助
答案 0 :(得分:1)
您需要这样做:
user.blacklists = [blacklist];
,然后保存用户实体。
有关更多信息,请在这里https://github.com/typeorm/typeorm/blob/master/docs/many-to-many-relations.md