Reputation: 63
I am defining entity fields in my NestJS project. I have ManyToOne realtion that is defined successfully. I have trouble finding the right way to define OneToMany relation to fit the syntax I used for other relation.
import {Entity,Column, PrimaryColumn, ManyToOne,JoinColumn,OneToMany} from "typeorm";
import { Account } from "./account.entity";
import { Balance } from "./balance.entity";
import { BaseEntity } from "./base.entity";
@Entity()
export class MainEntity extends BaseEntity {
@PrimaryColumn({
type: "varchar",
name: "id",
unique: true
})
id: string;
@ManyToOne(() => Account, { nullable: true })
@JoinColumn({
name: "account_id",
referencedColumnName: "id"
})
account: Account;
@OneToMay relation needs to be connected to the Balance entity and mappedBy paymentDevice field in it.
My try:
@OneToMany(() => Balance, ...)
balances: Balance[]
I am in NestJs and typescript so this is challenging for me.
Upvotes: 3
Views: 22073
Reputation: 100
Generally, TypeORM relations used in NestJS are simple and dev-friendly. The code which you've written defines parameters which are already predefined. For example,
@PrimaryColumn({
type: "varchar",
name: "id",
unique: true
})
This exact parameters is what defined by
@PrimaryColumn() // unique: true
id: string //varchar, name: id
So you can have the code just like below. For Account Entity,
@Entity()
export class Account {
@PrimaryColumn()
id: string;
@ManyToOne(type => Balance, balance => balance.id)
balance: Balance;
}
For Balance Entity
@Entity()
export class Balance {
@PrimaryColumn()
id: string;
@OneToMany(type => Account, account => account.id)
@JoinColumn({name: "account_id"})
// defining this is also optional because by default,
// the referenced foreign key is named as <column_name>_id or account_id
account: Account;
}
This will create a many-to-one relationship on Account and OneToMany on Balance entity. For more such examples, Refer: https://orkhan.gitbook.io/typeorm/docs/many-to-one-one-to-many-relations
Upvotes: 4