KDot
KDot

Reputation: 506

Many-to-many with custom column

I'm fairly new to Postgres (and Typeorm), and having a really hard time figuring out how to handle the following scenario:

Here is my schema:

// blog.entity.ts  omitting some fields for brevity
@Column()
@PrimaryGeneratedColumn()
id: number; 

@Column()
title: string; 

@OneToMany(() => BlogCategory, blogCategory => blogCategory.blog)
blogCategories: BlogCategory[];


// category.entity.ts
@Column()
@PrimaryGeneratedColumn()
id: number; 

@Column()
name: string;

@OneToMany(() => BlogCategory, blogCategory => blogCategory.category)
blogCategories: BlogCategory[];

// blog-category.entity.ts
@PrimaryGeneratedColumn()
id: number;

@Column()
is_primary: boolean;

@Column()
categoryId: number;

@Column()
blogId: number;

@ManyToOne( () => Category, category => category.blogCategories )
category: Category

@ManyToOne( () => Blog, blog => blog.blogCategories )
blog: Blog

I think that is all correct, but please correct me if I'm wrong. But the part I'm getting tripped up on now is how I actually handle the blog insert. I'm not sure how I handle adding the is_primary flag when necessary. Do I actually insert the blogCategory item manually? In which case I'd need to save the blog first, so that I'd have access to its id for the blogCategory. I was kind of under the impression that item would be created automatically.

Thanks in advance for anyone who is able to offer some insight!

Upvotes: 0

Views: 270

Answers (1)

You can achieve automatic insertion using {cascade: true} in your entity relation. Check this post How to save relation in @ManyToMany in typeORM

Other way you can do it using transaction. First save Blog, get the blog id then add item into BlogCategory See https://typeorm.io/#/transactions For an example see this pseudo code,

await getManager().transaction(async transactionalEntityManager => {
                const blog = await transactionalEntityManager.save(blogObject);
                blogCategory.blogId = blog.id;
                blogCategory.CategoryId = categoryId; // get categoryId from request body
                await transactionalEntityManager.save(blogCategory);
            });

Upvotes: 1

Related Questions