【问题标题】:TypeORM: Query Many-to-Many with Custom PropertiesTypeORM:使用自定义属性查询多对多
【发布时间】:2020-10-09 23:25:13
【问题描述】:

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

这是我的代码。

用户产品实体

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

}

我想知道。如何得到如上的结果?

【问题讨论】:

    标签: javascript mysql typescript nestjs typeorm


    【解决方案1】:

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

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

    您可以查看此文档:Find Options

    你可以这样做:

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

    【讨论】:

      猜你喜欢
      • 2021-02-08
      • 1970-01-01
      • 2021-12-26
      • 1970-01-01
      • 2021-11-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-02
      相关资源
      最近更新 更多