A Webb
A Webb

Reputation: 711

TypeORM TypeGraphQL OneToOne relation foreign key not working

I am trying to create a bi-drectional OneToOne relation with TypeORM and TypeGraphQL. I have two entities an Account.ts and Details.ts.

Right now, I can create Details in context of the account and it successfully populate the Account id from context.

However, in my Account table the detailsId field (foreign key) remains null and does not update. Therefore, I cannot query Details in context.

Here is my Account.ts entity

@ObjectType()
@Entity()
export class Account extends BaseEntity {
  @Field()
  @PrimaryGeneratedColumn()
  id: number;

  @OneToOne(() => Details, (detail) => detail.user, {cascade: true, eager: true})
  @Field(() => Details)
  @JoinColumn()
  detail: Details;
}

Here is my Details.ts entity.

@ObjectType()
@Entity()
export class Details extends BaseEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Field()
  @Column()
  title: string;

  @Field()
  @Column()
  userId: number;

  @OneToOne(() => Account, (user: Account) => user.detail)
  user: Account;
}

And here is my resolver.

@Mutation((_returns) => Details)
  @UseMiddleware(isAuth)
  async addDetails(
    @Arg("title") title: string,
    @Ctx() { req }: MyContext
  ): Promise<Details> {
    const details = this.detailsRepository.create({
      title,
      userId: req.session.userId,
    });
    return await this.detailsRepository.save(details);
  }

I believe that I am defining my entities wrong otherwise the foreign key would be available in the Account.ts table.

Any help is greatly appreciated.

Upvotes: 0

Views: 1101

Answers (1)

A Webb
A Webb

Reputation: 711

The problem was in my Mutation() - the Details were being saved but even with a { cascade: true } the saves were not being made to the account repository.

By explicitly saving the details to the user in the accountRepository after also saving the details in the detailsRepository.

@Mutation((_returns) => Boolean)
  @UseMiddleware(isAuth)
  async addDetails(
    @Arg("title") title: string,
    @Ctx() { req }: MyContext
  ) {
    const details = this.detailsRepository.create({
      title,
      userId: req.session.userId,
    });
    await this.detailsRepository.save(details);

    const user = await this.accountRepository.findOne(req.session.userId);

    if (!user) {
      return false;
    }

    if (user) {
      user.details = details;
      await this.accountRepository.save(user);
    }

    return true;
  }

Upvotes: 0

Related Questions