Getting a list of Id's for a OneToMany relationship in typeorm?

Viewed 212

Can anyone help ?

I can get the Id's on the relationship only on the JoinColumn end.

I have 2 entities, "dex" and "network".

A network can have many dex. A dex can only have one network.

If I do a "find" on "dex" then I get back the networkId - great!

If I do a "find" on the "network", I do not get back the list of Id's (looking for an array as a network can have my dex).

Here is the dex important parts

  @Column({ nullable: true })
  networkId?: number

  @ManyToOne(() => Network, (network) => network.dex)
  @JoinColumn()
  network: Network

And network important parts, I tried playing around with the "@RelationId" but it refused to work and got errors in the console. ( TypeORMError: Cannot find relation undefined. Wrong relation specified for @RelationId decorator )

  @OneToMany(() => Dex, (dex) => dex.network)
  dex?: Dex[]

  // @RelationId((dex: Dex) => dex.network) // you need to specify target relation
  // dexIds: number[]

I can do a find on the network and tell it to load the entities and then I get an array of "Dex" but I don't want to load the full object.

Is there something I am doing wrong.

Of course in the database, the Dex table has a networkId

Thanks in advance for any help.

A little stuck.

1 Answers

In fact you can't set an array of dexIds in your Network entity because this information is saved on the Dex entity.

To get all the data with your find method you can use the eager parameters like this and use a simple find method :

@OneToMany(() => Dex, (dex) => dex.network, {eager: true})
  dex?: Dex[]

Or you can juste specify the parameter "relations" with your query to add the list of your dex :

const network = await this.networks.findOne({
      where: {
        id: yourId
      },
      relations: ["dex"]})
Related