'Typeorm - Create new table which is linked to users table via `userId` column

I have users entity and table and now, I want to create new table user-settings with two columns where first column should be userId and other column is setting. How to create new entity user-settings-entity for typeORM which will contain these two columns and be linked with users table via userId? So every user has corresponding record in user-settings.



Solution 1:[1]

You can do that with one-to-one relations.

You can find the documentation here https://typeorm.io/#/one-to-one-relations

Solution 2:[2]

Sounds like ManyToMany relationship.

Here is an example:

import { Entity, JoinTable, ManyToMany, PrimaryGeneratedColumn } from "typeorm";

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

  @ManyToMany(() => Setting)
  @JoinTable()
  settings: Setting[];
}

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

If you want to have custom fields on the join table, you might need to create it as a separate entity then use @ManyToOne and @OneToMany.

More documentation: https://orkhan.gitbook.io/typeorm/docs/many-to-many-relations

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 David
Solution 2 Almaju