我在Channel
和User
之间有一种多对多的关系,它用于向订阅了某个通道的用户发送电子邮件通知。我正在开发一个功能,其中一个通道被分解为另一个通道,但我不知道如何将所有通知从分解通道转移到目标通道。
@Entity()
export class User {
@PrimaryColumn()
id: string
@Column()
createdAt: Date
@Column()
updatedAt: Date
@Column()
email: string
@ManyToMany(_type => Channel)
@JoinTable()
notifications: Channel[]
}
@Entity()
export class Channel {
@PrimaryColumn()
id: string
@Column()
createdAt: Date
@Column()
updatedAt: Date
}
async function transferNotifications(from: unknown, to: unknown): Promise<void> {
//?
}
发布于 2020-01-16 18:12:32
您至少有两个选项:
1.使用EntityManager
首先,获取与notification
具有已解析关系的所有User
实体。然后从所有获取的Channel
实体的notification
属性中删除旧的(已分解的) User
实体,并将新的Channel
实体添加到该数组中(如果它以前包含旧实体的话)。这将删除相应的连接表行,并向新通道添加一个新的连接表行。
明显的缺点是,连接将在所有行的三个表上执行,所有结果都加载到应用程序内存中。因此,对于较大的表来说,这不一定是一个好的解决方案。
2.使用QueryBuilder
一种更好的方法是通过添加自定义连接表实体来自己构建连接表。然后使用QueryBuilder
将旧通道的旧外键替换为新通道的id。
getRepository(UserChannel).createQueryBuilder()
.update()
.set({ channelId: '<new channel id>' })
.where(`channelId = :channelId`, { channelId: `<old channel id>`})
.execute();
@Entity()
export class User {
@PrimaryColumn()
id: string
@Column()
createdAt: Date
@Column()
updatedAt: Date
@Column()
email: string
@OneToMany(type => UserChannel)
userChannels: UserChannel[]
}
@Entity()
export class UserChannel {
@ManyToOne(type => User)
user!: User;
@Column({ primary: true })
userId!: string;
@ManyToOne(type => Channel)
channel!: channel;
@Column({ primary: true })
channelId!: string;
}
@Entity()
export class Channel {
@PrimaryColumn()
id: string
@Column()
createdAt: Date
@Column()
updatedAt: Date
}
发布于 2020-11-25 16:36:35
如果您正在使用NodeJs。您可以使用promises进行批量更新、删除或其他任何操作。
您需要做的是将所有更新map
到数组,然后使用Promise.all
解析它们。
新的更新。
updates = [{ id: 1, name: "Channel 1" }, { id: 2, name: "Channel 2"}];
批量更新代码
我
let promises = updates.map(update => {
let query = {id: update.id};
delete update.id;
return channelRepository
.update({id update.id}, update)
});
return await Promise.all(promises);
https://stackoverflow.com/questions/59760187
复制相似问题