Search code examples
typescripttypeormrawsqlcategory-abstractions

typeorm inner join and where problem - BaseEntity model


I use typeorm (^0.2.41) and define two model which extends from my custom BaseModel:

BaseModel:

import { BaseEntity } from 'typeorm';

export class BaseModel extends BaseEntity {
}

Category:

@Entity('Category', { schema: 'public' })
export class Category extends BaseModel {
  @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })
  id: number;

  @OneToMany(() => AbilityCategory, (abilityCategory) => abilityCategory.category, { onDelete: 'CASCADE' })
  abilityCategories: AbilityCategory[];
}

AbilityCategory:

@Entity('_ability_category', { schema: 'public' })
export class AbilityCategory extends BaseModel {
  @PrimaryGeneratedColumn({ type: 'integer', name: 'id' })
  id: number;

  @ManyToOne(() => Category, (category) => category.abilityCategories)
  @JoinColumn([{ name: 'categoryId', referencedColumnName: 'id' }])
  category: Category;
}

(I've removed unnecessary fields, before mention here)

and I write this query:

await Category.find({
  where: {
    type: 'JobCategory',
    'abilityCategories.id': 13
  },
  join: {
    alias: 'category',
    innerJoinAndSelect: { abilityCategories: 'category.abilityCategories' }
  },
  take: 5
}
);

but in raw sql query, it passes null to abilityCategories.id:

SELECT DISTINCT "distinctAlias"."category_id" as "ids_category_id"
FROM (SELECT "category"."id" AS "category_id"
      FROM "public"."Category" "category"
               INNER JOIN "public"."_ability_category" "abilityCategories"
      ON "abilityCategories"."categoryId" = "category"."id"
      WHERE ("category"."type" = $1 AND "abilityCategories"."id" = $2)) "distinctAlias"
ORDER BY "category_id" ASC
LIMIT 5 -- PARAMETERS: ["JobCategory",null]

is there anyone to help me find out the reason of null value for second parameter?


Solution

  • it is related to this issue on GitHub

    https://github.com/typeorm/typeorm/issues/3890