首页 > 解决方案 > 如何在通过 JoinTable 连接的多对多关系中自我引用 typeorm 中的表?

问题描述

我是使用 typeorm 的新手,但确实了解 typeorm 中的关系概念。我正在使用带有 typeorm 的 nestjs 并有 2 个表,即 Products 和 Links,它们具有多对多的关系。

链接实体.ts

@Entity({ name: 'links' })
export class Link {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  code: string;

  @ManyToOne(() => User)
  @JoinColumn({ name: 'user_id' })
  user: User;

  @ManyToMany(() => Product)
  @JoinTable({
    name: 'link_products',
    joinColumn: { name: 'link_id', referencedColumnName: 'id' },
    inverseJoinColumn: { name: 'product_id', referencedColumnName: 'id' },
  })
  product: Product[];

  ...
}

产品实体.ts

@Entity({ name: 'products' })
export class Product {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  title: string;

  @Column()
  image: string;

  @Column()
  description: string;

  @Column()
  price: number;
}

链接控制器.ts

export class LinkController {
  constructor(
    private readonly linkService: LinkService,
    private authService: AuthService,
  ) {}

  @UseGuards(AuthGuard)
  @Post('ambassador/links')
  async create(@Body('products') products: number[], @Req() request: Request) {
    const user = await this.authService.user(request);
    return this.linkService.create({
      code: Math.random().toString(36).substr(6),
      user,
      products: products.map((id) => ({ id })),
    });
  }

  @Get('checkout/links/:code')
  async link(@Param('code') code: string) {
    return await this.linkService.findOne({
      code,
      relations: ['user', 'product'],
    });
  }

  ...
}

在链接控制器中,我正在为大使创建一个链接,其主体包含一系列产品 ID。这将返回一个随机代码。我想要的是,当我点击 Get route copy 并粘贴收到的代码时,它应该显示与该链接关联的所有产品,但我得到的是一个空数组

示例演示:

  1. 为链接插入产品

    发布:http://localhost:8000/api/ambassador/links

    正文:{“产品”:[6,2]}

输出:

{
    "code": "e37dufa",
    "user": {
        "id": 11,
        "first_name": "ambassador",
        "last_name": "ambassador",
        "email": "ambassador@ambassador.com",
        "is_ambassador": true
    },
    "products": [
        {
            "id": 6
        },
        {
            "id": 2
        }
    ],
    "id": 2
}
  1. 获取链接:

    获取:http://localhost:8000/api/checkout/links/e37dufa

输出:

{
    "id": 1,
    "code": "e37dufa",
    "user": {
        "id": 11,
        "first_name": "ambassador",
        "last_name": "ambassador",
        "email": "ambassador@ambassador.com",
        "is_ambassador": true
    },
    "product": []
}

非常感谢任何帮助或建议。

标签: nestjsrelationshipentity-relationshiptypeorm

解决方案


您可以绑定两种方式,如下所示。现在您可以访问link.productsproduct.links

链接实体.ts

@ManyToMany(() => Product, product => product.links)
@JoinTable()
products: Product[]

产品实体.ts

@ManyToMany(() => Link, link => link.products)
links: Link[]


推荐阅读