类型ORM:使用自定义属性查询多对多



大家 我是TypeORM的新手,我需要一些帮助。

我尝试使用自定义属性创建多对多关系,例如此处的文档

这是我的问题。

我想要这样的查询结果..

{
"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[];
}

我想知道。如何获得上述结果?

我想你想知道如何加载子关系

关系 - 关系需要加载到主体中。也可以加载子关系(连接和左连接和选择的简写(

您可以查看此文档:查找选项

你可以这样做:

const user = await this.userRepository.findOne({
where: { id },
relations: ["products.product"],
});

最新更新