'TypeORM: Query Many-to-Many with Custom Properties

everyone I'm new in TypeORM and I need some help.

I try to create many-to-many relations with custom properties like this docs here

And here my problems.

I want query result like this..

{
    "id": 1,
    "username": "John Doe",
    "products": [
        {
            "id": 1,
            "title": 'A shirt',
            "description": 'lorem ipsum'
        }
    ]
}

But I got...

{
    "id": 1,
    "username": "John Doe",
    "products": [
        {
            "id": 1,
            "userId": 1,
            "productId":1
        }
    ]
}

Here how I query

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

Here is my code.

UserProduct Entity

// 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

// 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

// 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?



Solution 1:[1]

I think you want to know how to load the sub-relations

relations - relations need to be loaded with the main entity. Sub-relations can also be loaded (shorthand for join and leftJoinAndSelect)

You can check this doc: Find Options

You can do like this:

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Sabito 錆兎 stands with Ukraine