【问题标题】:ManyToOne relation: update parent on change多对一关系:在更改时更新父级
【发布时间】:2021-04-24 05:25:05
【问题描述】:

在我的 NestJS 项目中,我有以下具有 OneToMany / ManyToOne 关系的实体:

faculty.entity.ts:

@OneToMany(
type => Society,
society => society.faculty,
{ eager: false })
societies: Society[];

society.entity.ts:

@ManyToOne(
type => Faculty,
faculty => faculty.societies,
{ onDelete: 'CASCADE' })
@JoinColumn()
faculty: Faculty;

@Column()
facultyId: number;

我想实现一个功能来改变一个社会绑定的学院。

所以,在socials.service.ts 我有补丁方法:

async patch(id: number, patchSocietyDto: PatchSocietyDto): Promise<Society> {
  const society = await this.findOne(id);

  for (const prop in patchSocietyDto) society[prop] = patchSocietyDto[prop];

  try {
    await society.save();
  } catch (err) {
    throw new InternalServerErrorException(err);
  }

  return society;
}

我想在请求正文中传递“facultyId”属性,删除现有关系,然后在 ID 为“facultyId”的 Faculty 之间添加一个新关系。

我怎样才能做到这一点?

【问题讨论】:

    标签: nestjs typeorm


    【解决方案1】:

    我终于找到了解决方案。我唯一需要更改的是在一对多关系中将“eager”选项设置为 true:

    @OneToMany(
      type => Society,
      society => society.faculty,
      { eager: true },
    )
    societies: Society[];
    

    通过此更改,通过为“facultyId”属性传递新值来更新关系。

    【讨论】:

      猜你喜欢
      • 2019-01-23
      • 2018-02-17
      • 1970-01-01
      • 2012-06-26
      • 1970-01-01
      • 1970-01-01
      • 2018-01-06
      • 1970-01-01
      • 2017-01-30
      相关资源
      最近更新 更多