TypeORM: запрос "многие ко многим" с настраиваемыми свойствами - PullRequest
1 голос
/ 19 июня 2020
• 1000 *

А вот и мои проблемы.

Мне нужен такой результат запроса ..

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

}

Хотелось бы знать. Как получить такой результат?

...