TypeORM:使用自定义属性查询多对多

时间:2020-06-19 16:37:10

标签: javascript mysql typescript nestjs typeorm

每个人我都是TypeORM的新手,我需要一些帮助。

我尝试使用诸如docs here

这样的自定义属性创建多对多关系

这是我的问题。

我想要这样的查询结果。

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

这是我的代码。

UserProduct实体

// 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 User 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[];

}

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

1 个答案:

答案 0 :(得分:0)

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

<块引用>

关系 - 关系需要与主要实体一起加载。也可以加载子关系(join 和 leftJoinAndSelect 的简写)

您可以查看此文档:Find Options

你可以这样做:

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