nestjs - 如何在通过 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 并粘贴收到的代码时,它应该显示与该链接关联的所有产品,但我得到的是一个空数组
示例演示:
为链接插入产品
发布: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
}
获取链接:
获取: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": []
}
非常感谢任何帮助或建议。
解决方案
您可以绑定两种方式,如下所示。现在您可以访问link.products
或product.links
。
链接实体.ts
@ManyToMany(() => Product, product => product.links)
@JoinTable()
products: Product[]
产品实体.ts
@ManyToMany(() => Link, link => link.products)
links: Link[]
推荐阅读
- linux - Cron 不运行 sh 脚本
- python - NodeJS Grant - 带有 Django Oauth Toolkit 应用程序的 Oauth
- c# - EF 数据设置 ViewModel
- sql - 如何将选择表达式的结果保存为变量?
- azure - How to Periodically delete data in Azure SQL DB
- arrays - 根据元素之间的某些匹配删除数组行
- python - 通过 Jupyter 执行 Python:调用 quit() 和 exit() 引发 NameError
- python - 如何在 SciPy 稀疏矩阵 CSR_Matrix 中保留插入顺序?
- php - 将 Laravel 集合中的 id 参数传递给 Vue 组件
- r - 使用 RCurl::getURL() 从安全 FTP 获取数据