简体   繁体   中英

How should i make mapping table relationship logic in the nestjs typeorm?

I'm writing because I have a question while dealing with the mapping table. When creating a user on a web page, I want to put existing information and data called equipment. Each user can start with multiple equipment, so they created a mapping table like a picture to resolve the N:M relationship.

However, in order to put data in the mapping table in typeorm, you must first create a user object and an item object. After turning the loop as many times as the number of equipment set to the user to find the equipment number received from the web, we are creating an equipment object and inserting it into the mapping table.

Is there a better way than what I'm doing?

        await Promise.all(
            items.map(async (element) => {
                const uItem = new UserItem();
                uItem.item = element.item;
                uItem.user = user;
                uItem.period = element.period;
                await transactionManager.save(uItem);
            })
        );

在此处输入图像描述

typeORM has an easy solution for it So you define your 2 main entities like this

@Entity()
export class Item{
  @PrimaryGeneratedColumn('uuid')
  id: string; // or whatever you like

  @OneToMany(() => UserItems, userItem => userItem.item, {
    nullable: true,
    cascade: true,
  })
  userItems: UserItem[];
...
@Entity()
export class User{
  @PrimaryGeneratedColumn('uuid')
  id: string; // or whatever you like

  @OneToMany(() => UserItems, userItem => userItem.user, {
    nullable: true,
    cascade: true,
  })
  userItems: UserItem[];
...

And your mapping class as following:

@Entity()
export class UserItem{
  @PrimaryGeneratedColumn('uuid')
  id: string; // or whatever you like

  @ManyToOne(() => User, {
    onDelete: 'CASCADE', // decide on delete logic
  })
  user: User;

  @ManyToOne(() => Item, {
    onDelete: 'CASCADE', // decide on delete logic
  })
  item: Item;
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM