我在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> {
//?
}
答案 0 :(得分:3)
您至少有两个选择:
1。使用EntityManager
首先,获取所有与User
有已解决关系的notification
实体。然后从所有提取的Channel
实体的notification
属性的User
属性中删除旧的(已分解)Channel
实体,如果新的QueryBuilder
实体先前包含旧的实体,则将其添加到该数组中。这将删除相应的联接表行,并在新通道中添加一个新行。
明显的缺点是,联接将在所有行的三个表上执行,所有结果都加载到应用程序内存中。因此,不一定是大表的好解决方案。
2。使用QueryBuilder
更好的方法是通过添加自定义联接表实体来自己构建联接表。然后使用getRepository(UserChannel).createQueryBuilder()
.update()
.set({ channelId: '<new channel id>' })
.where(`channelId = :channelId`, { channelId: `<old channel id>`})
.execute();
将旧的外键替换为新通道的ID。
@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
}
import paho.mqtt.publish as publish
publish.single("home/floor_1/room", "payload", hostname="mqtt.eclipse.org")
答案 1 :(得分:0)
如果使用的是NodeJ。您可以使用Promise进行批量更新,删除或其他任何操作。
您需要做的是map
对数组的所有更新,然后使用Promise.all
对其进行解析。
新更新。
updates = [{ id: 1, name: "Channel 1" }, { id: 2, name: "Channel 2"}];
批量更新代码
l
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);