plumier icon indicating copy to clipboard operation
plumier copied to clipboard

When defining @RelationId column in entity, the nested genereictController does not populate that field

Open almontasser opened this issue 3 years ago • 3 comments

@genericController()
@Entity()
export class Country extends EntityBase {
  @Column({ nullable: false, unique: true })
  name!: String;

  @Column({ nullable: false })
  flagCode!: string;

  @api.readonly()
  @api.writeonly()
  @api.hideRelations()
  @genericController()
  @OneToMany(() => City, (city) => city.country)
  cities!: City[];
}

@Entity()
export class City extends EntityBase {
  @Column({ nullable: false })
  name!: String;

  @api.readonly()
  @api.writeonly()
  @api.hideRelations()
  @ManyToOne(() => Country)
  country!: Country;

  @RelationId((city: City) => city.country)
  countryId: number;
}

GET /api/countries/1/cities

returns

[
  {
    "name": "Tripolo",
    "createdAt": "2021-12-04T15:50:52.457Z",
    "updatedAt": "2021-12-04T15:50:52.457Z",
    "deleted": false,
    "id": 1
  }
]

The field countryId not populated

almontasser avatar Dec 05 '21 11:12 almontasser

And if I replaced @RelationId() by @Column(), the GetMany returns an empty array, and the generated sql query looks like this:

SELECT `City`.`id` AS `City_id`, `City`.`createdAt` AS `City_createdAt`, `City`.`updatedAt` AS `City_updatedAt`, `City`.`deleted` AS `City_deleted`, `City`.`name` AS `City_name`, `City`.`countryId` AS `City_countryId` FROM `city` `City` WHERE `City`.`countryId` = ? LIMIT 50 -- PARAMETERS: [null]

almontasser avatar Dec 05 '21 12:12 almontasser

It looks like a typeorm problem, if you define a relationId column you can't query with the relation name

almontasser avatar Dec 05 '21 12:12 almontasser

@almontasser thanks for the clarification. can you try to select it manually? GET /api/countries/1/cities?select=name,countryId, actually I doubt it will work, if the result is undefined from the query itself.

FYI: the appropriate code to select the data is here https://github.com/plumier/plumier/blob/03a338cbd3949d87760411059caf56ccbdf9d6b9/packages/typeorm/src/repository.ts#L67-L75

In your context this.relation.childProperty is the cities property. selection.relations list of relations selected using ?select=col1,col2,col3 (I barely remember that I processed @RelationId() is included here, so maybe this is the issue?

ktutnik avatar Dec 06 '21 01:12 ktutnik