Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

graphql - Creating related entity after Insertion Typeorm

I have 2 Entities:

  1. User
  2. Promo

I would like to create a Promo entity, which has a oneToOne relationship with the User entity, every time a User entity is created/inserted.

I am new to typeorm, so I'm not sure what the best way to achieve this would be.

I have tried using subscribers can't seem to achieve the desired functionality. Another option would be to do this inside the GraphQL Resolver, but this seems messy to me.

What is considered best practice when trying to do this?

question from:https://stackoverflow.com/questions/65661725/creating-related-entity-after-insertion-typeorm

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use fully typeorm to save all required data, but make sure you have created entities with proper connection between them :

// Promo.ts

@Index()
@OneToOne(() => User, user => user.promo)
@JoinColumn()
user: User

I have added @JoinColumn to Promo expecting, that Promo Entity will have userId in table.

// User.ts

@OneToOne(() => Promo, promo => promo.user)
promo: Promo

In Repository, for example, you can use Transaction operation and save User and right after save this user with other required Promo details:

saveUser(user: User) {
  return getManager().transaction(async (manager) => {
    const result = await manager
      .getRepository(User)
      .createQueryBuilder()
      .insert()
      .values(user)
      .execute()
    
    // check on result emptiness

    const createdUser = await manager
      .getRepository(User)
      .createQueryBuilder()
      .where('id=:id',{id: result.identifiers[0].id})
      .getOne()

    await manager
      .getRepository(Promo)
      .createQueryBuilder()
      .insert()
      .values({user: createdUser})
      .execute()
  })
}

It will save in one transaction first User and after Promo with this user.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...