chimek0
chimek0

Reputation: 21

Typeorm postgres: Create relation by unique column (not PK) as constraint

so I'm struglling for a while now. I'm trying to model my custom join table in postgres using typeorm.

I want to set non PK column ('uuid') as relation constraint, but I can't find any solution.

I have two already existing tables, lets name them A and B.

@Entity()
export class A {
  @PrimaryGeneratedColumn('uuid')
  uuid: string;

 ...
}

@Entity()
@Unique(['uuid'])
export class B {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  @Generated('uuid')
  uuid: string;

 ...
}

So now I want my join table to be

@Entity()
@Unique(['a', 'b'])
export class AB {
  @PrimaryGeneratedColumn('uuid')
  uuid: string;

  @ManyToOne(() => A, { nullable: false })
  a: A;

  @ManyToOne(() => B, { nullable: false })
  b: B;
}

and then I would like to save new entity like repository.save({ a: { uuid: uuid }, b: { uuid: uuid }}); It works when I try to save relation B with its PK ('id') but aint working with uuid.

I'd be greateful for any help cheers

Upvotes: 1

Views: 2321

Answers (1)

chimek0
chimek0

Reputation: 21

Ok, so I figure it out, in case anyone has the same problem, here is my solution. I've removed @Unique('uuid') from table B and declared it directly on column, I also had to mark column as type: 'uuid', then on join table I've used @JoinColumn decorator pointing to uuid column.

@Entity()
export class B {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ unique: true, type: 'uuid' })
  @Generated('uuid')
  uuid: string;

 ...
}

@Entity()
@Unique(['a', 'b'])
export class AB {
  @PrimaryGeneratedColumn('uuid')
  uuid: string;

  @ManyToOne(() => A, { nullable: false })
  a: A;

  @ManyToOne(() => B, { nullable: false })
  @JoinColumn({ referencedColumnName: 'uuid' })
  b: B;
}

Upvotes: 1

Related Questions