各位,我是 TypeORM 的新手,我需要一些帮助。
我尝试使用这样的自定义属性创建多对多关系 docs here
And here my problems.
我想要这样的查询结果..
{
"id": 1,
"username": "John Doe",
"products": [
{
"id": 1,
"title": 'A shirt',
"description": 'lorem ipsum'
}
]
}
但是我得到了...
{
"id": 1,
"username": "John Doe",
"products": [
{
"id": 1,
"userId": 1,
"productId":1
}
]
}
这里是我查询的方式
const user = await this.userRepository.findOne({
where: { id },
relations: ["products"],
});
这是我的代码。
用户产品实体
// user-product.entity.ts
@Entity()
export class UserProduct extends BaseEntity {
@PrimaryColumn()
public id: number;
@Column()
public userId!: number;
@Column()
public productId!: number;
@ManyToOne(
() => User,
(user) => user.products
)
public user!: User;
@ManyToOne(
() => Product,
(product) => product.users
)
public product!: Product;
}
用户实体
// user.entity.ts
@Entity()
export class User extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
username: string;
@OneToMany(()=> UserProduct, userToProduct => userToProduct.user)
public products!: UserProduct[];
}
产品实体
// product.entity.ts
@Entity()
export class Product extends BaseEntity {
@PrimaryGeneratedColumn()
id: number;
@Column()
title: string;
@Column({ nullable: true })
subtitle: string;
@Column({ nullable: true })
description: string;
@OneToMany(
() => UserProduct,
(userProduct) => userProduct.product
)
public users!: UserProduct[];
}
I would like to know. How to get the result like the above?
最佳答案
我想你想知道如何加载子关系
relations - relations need to be loaded with the main entity. Sub-relations can also be loaded (shorthand for join and leftJoinAndSelect)
您可以查看此文档:Find Options
你可以这样做:
const user = await this.userRepository.findOne({
where: { id },
relations: ["products.product"],
});
关于javascript - TypeORM:使用自定义属性查询多对多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62474805/