【问题标题】:Mikro-Orm - ManyToMany Relationship how can I delete reference in PivotTable?Mikro-Orm - 多对多关系如何删除数据透视表中的引用?
【发布时间】:2022-11-01 17:26:14
【问题描述】:

我将 NestJS 与 mikro-Orm 一起使用,并且对我的所有 manyToMany 关系都有一个奇怪的行为。

@ObjectType()
@Entity()
export class Realty {
    @Field(() => ID)
    @PrimaryKey({ columnType: "uuid" })
    id: string = v4();

    @Field(() => [Contact])
    @ManyToMany(() => Contact, (contact) => contact.realties)
    contacts: Collection<Contact>;  
}
@ObjectType()
@Entity()
export class Contact {
    @Field(() => ID)
    @PrimaryKey({ columnType: "uuid" })
    id: string = v4();

    @Field(() => [Realty])
    @ManyToMany(() => Realty, (realty) => realty.contacts, { owner: true })
    realties: Collection<Realty>;
}

当我想从联系人中删除 realtyReference 时,效果很好,并且 Contact_Realty PivotTable 中的行被删除。但是,当我尝试从不动产中删除 contactReference 时,什么也没有发生。这只对拥有方有效吗?

ContactsService(工作):

async update(updateContactInput: UpdateContactInput) {
        const { id, realtyIds } = updateContactInput;

        const contact = await this.findOneOrFail(id);

        const updated = this.contactsRepository.assign(contact, {
            realties: await this.realtiesService.find(realtyIds),   
        });

        await this.contactsRepository.persistAndFlush(updated);
        return updated;
    }

房地产服务(返回正确的更新实体,但不删除数据透视表中的行):

async update(updateRealtyGeneralInput: UpdateRealtyGeneralInput) {
        const { id, contactIds } = updateRealtyGeneralInput;

        const realty = await this.realtiesService.findOneOrFail(id);

        const updated = this.realtiesRepository.assign(realty, {
            contacts: await this.contactsService.find(contactIds),
        });

        await this.realtiesRepository.persistAndFlush(updated);

        return updated;
    }

两者都返回正确的更新实体,但只有 ContactsService 实际删除了数据透视表中的行。

非常感谢一些帮助,非常感谢!

我想从不动产中删除一个或多个联系人,但无法使其正常工作。难道我做错了什么?

【问题讨论】:

    标签: orm many-to-many mikro-orm


    【解决方案1】:

    您总是需要初始化/填充您的 M:N 集合的拥有方,而在第二个示例中您显然没有这样做。在您的情况下,它是Contact.realties,因此,如果您想从反面操作此集合,则从反面添加/删除的所有实体都需要填充拥有方。在计算变更集时,只考虑拥有方。我需要重新审视一下,由于最近的变化,比如 v5.5 中添加的参考更新,我们可能能够对此进行改进。

    此外,您的代码中存在一些误解。 assign 改变参数,它不返回“修改后的实体”,它改变你在第一个参数中传递的那个。如果该实体已经被管理(如您的情况),则再次保留它是没有意义的,只需刷新即可。

    async update(updateRealtyGeneralInput: UpdateRealtyGeneralInput) {
      const { id, contactIds } = updateRealtyGeneralInput;
    
      const realty = await this.em.findOneOrFail(Realty, id);
    
      this.realtiesRepository.assign(realty, {
        contacts: await this.em.find(Contact, contactIds, { populate: ['realties'] }),
      });
    
      await this.em.flush(updated);
    
      return realty;
    }
    

    【讨论】:

      猜你喜欢
      • 2015-02-11
      • 1970-01-01
      • 2015-02-04
      • 1970-01-01
      • 2016-02-02
      • 1970-01-01
      • 2023-02-05
      • 1970-01-01
      • 2018-09-23
      相关资源
      最近更新 更多