Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 764
ThomasReggi Avatar asked Feb 07 '26 03:02

ThomasReggi


1 Answers

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.

like image 90
JudgeFudge Avatar answered Feb 09 '26 08:02

JudgeFudge



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!