Typeorm 不返回所有数据

2021-09-11 00:00:00 node.js mysql nestjs typeorm

我遇到了无法获取 Typeorm 返回的所有数据的问题.

I have an issue where I could not get all of the data returned by Typeorm.

这里是相关实体.

媒体实体:

@Entity()
export class Media {
  @PrimaryGeneratedColumn()
  id: number;

  @Column('text')
  type: string;
}

类别实体:

@Entity()
export class Category {
  @PrimaryGeneratedColumn()
  id: number;

  @OneToMany((type) => Model, (model) => model.category)
  models: Model[];

  @ManyToMany(() => Media, { cascade: true })
  @JoinTable()
  medias: Media[];
}

模型实体:

@Entity()
export class Model {
  @PrimaryGeneratedColumn()
  id: number;

  @Column()
  manufacturer: string;
....
  @ManyToOne(() => Category, (category) => category.models)
  category: Category;

  @ManyToMany(() => Media, { cascade: true })
  @JoinTable()
  medias: Media[];
}

当我执行这段代码时:

 const getOneCategory: Category = await this.categoryRepository
        .createQueryBuilder('category')
        .leftJoinAndSelect('category.medias', 'media')
        .leftJoinAndSelect('category.models', 'model')
        .getOne();

它回来了

{
    "id": 1,
    "name": "Luxury",
    "medias": [
      {
        "id": 1,
        "type": "image",
        "url": "images/car-categories/luxury.png"
      },
      {
        "id": 2,
        "type": "the boy on fireeeeeeee",
        "url": "httpezdths:/whjrbfkjaberkjPokemonssss"
      }
    ],
    "models": [
      {
        "id": 2,
        "manufacturer": "Lamborghini1",
        "model": "Aventador1",
        "shortName": "Aventador1",
        "zeroToHundred": "3.53",
        "transmission": "AMT1",
        "driveTrain": "AWD1",
        "topSpeed": 3203,
        "engine": "2.9L1"
// THE MEDIA ATTRIBUTE is MISSING
      },
    ]
  }

模型对象键中缺少 media 属性.我想像这样获取 model 对象键中的媒体数组

The media attribute is missing from the model object key. I would like to get the array of media in the model object key like this

...

models: [{
      "id": 1,
      "manufacturer": "Lamborghini1",
      "model": "Aventador1",
      "shortName": "Aventador1",
      "zeroToHundred": "3.53",
      "transmission": "AMT1",
      "driveTrain": "AWD1",
      "topSpeed": 3203,
      "engine": "2.9L1",
      "medias": [ //I WANT TO GET THIS VALUE AS WELL
        {
          "id": 3,
          "type": "jasretdhsdfl1",
          "url": "httpezdths://wsrg1111111"
        }
      ]
    },]

...

感谢任何帮助.

推荐答案

通过添加模型和媒体之间的连接,您可以获得想要的结果:

You get the wanted result by adding the join between model and media :

 const getOneCategory: Category = await this.categoryRepository
    .createQueryBuilder('category')
    .leftJoinAndSelect('category.medias', 'media')
    .leftJoinAndSelect('category.models', 'model')
    .leftJoinAndSelect('model.medias', 'medias') // this line 
    .getOne();

相关文章