0

I need to store 2 records which relates to each other. Table1 has relation to Table2 and at the same time Table2 has relation to Table1

The code of creation and storing records:

    const account = this.accountRepository.create({ 
      // ...
    });
    const user = this.authUserRepository.create({
      account,
      // ...
    });

    account.primary_user = user;

    await Promise.all([
      this.accountRepository.save(account),
      this.authUserRepository.save(user),
    ]);

Thats how entities look like:

// auth-user.entity.ts
@Entity({ name: 'auth_user' })
export class AuthUser {
  @PrimaryGeneratedColumn('increment')
  public id: number;
  
  @OneToOne(() => Account, { nullable: true })
  @JoinColumn({ name: 'account_id', referencedColumnName: 'id' })
  public account: Account;
}

// account.entity.ts
@Entity({ name: 'account' })
export class Account {
  @PrimaryGeneratedColumn('increment')
  public id: number;

  @OneToOne(() => AuthUser, {
    nullable: true,
    onDelete: 'SET NULL',
    onUpdate: 'CASCADE',
  })
  @JoinColumn({ name: 'primary_user_id', referencedColumnName: 'id' })
  public primary_user: AuthUser;
}

In DB I see that no any of related ids are filled: account.primary_user_id is null and auth_user.account_id is null

PS: I am not the person who designed this DB structure I must follow it

1 Answer 1

1

I don't know if the Promise.all() is working for your first two calls, I would try this instead just to be sure:

const [account, user] = Promise.all([
  await this.accountRepository.create({ // ... })
  await this.authUserRepository.create({ // ... })
]);

account.primary_user = user;

await this.accountRepository.save(account);

You could also change you cascading options to work on insert and update so you could do:

const account = {
  ...
  user: {}
}
await this.accountRepository.save(account);
// save will create if item not found with id
Sign up to request clarification or add additional context in comments.

2 Comments

Yes, thank you. This approach works, but we need to save the same record twice const account = this.accountRepository.create({}); const user = this.authUserRepository.create({ account }); account.primary_user = user; await this.accountRepository.save(account); await Promise.all([ this.accountRepository.save(account), this.authUserRepository.save(user), ]);
You could do .save(account) twice then, but I really don't see why you need to duplicate the data.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.