Search code examples
postgresqltypeorm

Typeorm get relations for array column of ids


I am looking to add a column of id's to Invoice with the items from the invoice.

I'm getting the error

Entity metadata for Invoice#invoiceItems was not found.

I've tried these two options:

class Invoice {

  @OneToMany(type => InvoiceItem, invoiceItem => invoiceItem.id)
  @JoinColumn()
  invoiceItems: InvoiceItem[]
  @RelationId((self: Invoice) => self.invoiceItems)
  invoiceItemIds: number[]

}

and

class Invoice {

  @OneToMany(type => InvoiceItem, invoiceItem => invoiceItem.id)
  @JoinColumn()
  invoiceItems: InvoiceItem[]
  @Column({ type: PostgresColumns.number, array: true, nullable: false, default: {} })
  invoiceItemIds: number[]

How can I add relations for an array of ids?


Solution

  • You can't use @JoinColumn for @OneToMany (see the docs), you need to configure that in your InvoiceItem class:

    @Entity()
    class Invoice { 
        @OneToMany(type => InvoiceItem, invoiceItem => invoiceItem.invoice) 
        invoiceItems: InvoiceItem[];
    
        @RelationId((self: Invoice) => self.invoiceItems) 
        invoiceItemIds: number[] 
    }
    
    @Entity()
    class InvoiceItem { 
        ...
        @ManyToOne(type => Invoice, invoice => invoice.invoiceItems) 
        invoice: Invoice;
        ...
    }
    

    I haven't worked with @RelationId yet, but if you correctly join the InvoiceItems this should work.