Reputation: 391
I'm writing because I have a question while dealing with the mapping table. When creating a user on a web page, I want to put existing information and data called equipment. Each user can start with multiple equipment, so they created a mapping table like a picture to resolve the N:M relationship.
However, in order to put data in the mapping table in typeorm, you must first create a user object and an item object. After turning the loop as many times as the number of equipment set to the user to find the equipment number received from the web, we are creating an equipment object and inserting it into the mapping table.
Is there a better way than what I'm doing?
await Promise.all(
items.map(async (element) => {
const uItem = new UserItem();
uItem.item = element.item;
uItem.user = user;
uItem.period = element.period;
await transactionManager.save(uItem);
})
);
Upvotes: 0
Views: 1529
Reputation: 1098
typeORM has an easy solution for it So you define your 2 main entities like this
@Entity()
export class Item{
@PrimaryGeneratedColumn('uuid')
id: string; // or whatever you like
@OneToMany(() => UserItems, userItem => userItem.item, {
nullable: true,
cascade: true,
})
userItems: UserItem[];
...
@Entity()
export class User{
@PrimaryGeneratedColumn('uuid')
id: string; // or whatever you like
@OneToMany(() => UserItems, userItem => userItem.user, {
nullable: true,
cascade: true,
})
userItems: UserItem[];
...
And your mapping class as following:
@Entity()
export class UserItem{
@PrimaryGeneratedColumn('uuid')
id: string; // or whatever you like
@ManyToOne(() => User, {
onDelete: 'CASCADE', // decide on delete logic
})
user: User;
@ManyToOne(() => Item, {
onDelete: 'CASCADE', // decide on delete logic
})
item: Item;
...
Upvotes: 1