Damon
Damon

Reputation: 4524

How can I create a UUID FK column in NestJS?

I am running into an odd issue where I can't create a FK relationship between two entities.

// organization.entity.ts

@PrimaryGeneratedColumn('uuid')
  id: string;

...

@OneToMany(() => User, (user) => user.organization)
  users: User[];
// user.entity.ts

@PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({
    type: 'uuid',
  })
  organizationId: string;

...

@ManyToOne(() => Organization, (organization) => organization.users)
  organization: Organization;

In my ormconfig.json file I have these settings (among connection creds)

...
"logging": true,
  "entities": [
    "dist/**/*.entity{.ts,.js}"
  ],
  "synchronize": true
...

I am using "typeorm": "^0.2.45" in my package.json file.

Key columns "organizationId" and "id" are of incompatible types: character varying and uuid.

How can I create an FK relationship between users & organizations?

Upvotes: 0

Views: 2611

Answers (1)

Jay Godhani
Jay Godhani

Reputation: 396

So from your question I understood is you want a "organizationId" field in your users table which will be a FK.

To create OnetoMany Relation between Organization and users do as below:

// organization.entity.ts

@Entity({ name: 'organizations' })
export class Organization {
  @PrimaryGeneratedColumn('uuid')
  id: string;

...

  @OneToMany(() => User, (user) => user.organization)
  users: User[];
}
// user.entity.ts

@Entity({ name: 'users' })
export class User {
  @PrimaryGeneratedColumn('uuid')
  id: string;

  @Column({ type: 'uuid' })
  organizationId: string;

...

  @ManyToOne(() => Organization, (organization) => organization.users)
  @JoinColumn({ name: 'organizationId' })
  organization: Organization;
}

Upvotes: 3

Related Questions