【问题标题】:Typeorm update record in OneToMany relationOneToMany 关系中的 Typeorm 更新记录
【发布时间】:2021-02-20 19:46:53
【问题描述】:

我有以下两个实体,它们之间存在 OneToMany/ManyToOne 关系:

@Entity({ name: 'user' })
export class User {
  @PrimaryGeneratedColumn('increment')
  id: number;

  @Column({ type: 'varchar' })
  firstName: string;

  @Column({ type: 'varchar' })
  lastName: string;

  @ManyToOne(() => Group, group => group.id)
  @JoinColumn({ name: 'groupId' })
  group: Group;

  @Column({ type: 'integer' })
  groupId: number;
}
@Entity({ name: 'group' })
export class Group {
  @PrimaryGeneratedColumn('increment')
  id: number;

  @Column({ type: 'varchar' })
  name: string;

  @OneToMany(() => User, user => user.group)
  members: User[];
}

当我在我的组存储库中创建一个新组时,我可以按如下方式添加现有成员:

const group = new Group();
group.name = 'Test';
group.members = [{ id: 1 }, { id: 2 }]; // user ids
this.save(group);

我想知道是否可以以类似的方式更新现有成员。例如,如果一个 id 为 1 的组有两个成员:

{ id: 1, firstName: 'Member', lastName: 'One', groupId: 1 }
{ id: 2, firstName: 'Member', lastName: 'Two', groupId: 1 }

是否可以通过 OneToMany 关系以与我添加成员类似的方式更新成员?类似于(编造这个):

const group = await repository.findOne(groupId, { relations: ['members'] });
group.members = [{ id: 1, firstName: 'Updated' }]; // this would update the firstName of member with id 1 if it exists in the relation
repository.save(group);

谢谢!

【问题讨论】:

  • 你试过关系中的 {cascade:true} 选项吗?

标签: postgresql nestjs typeorm


【解决方案1】:

typeorm 中没有内置功能可以从基本实体更新特定的相关实体。但是,如果您想这样做,则可以添加一个通用函数来更新基表及其关系。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-04
    • 1970-01-01
    • 2020-10-25
    • 1970-01-01
    • 2019-12-02
    • 1970-01-01
    • 1970-01-01
    • 2021-05-17
    相关资源
    最近更新 更多