Maintain many to many relation #419
-
Suppose we have Post, Category and PostCategory entities: @Entity('posts')
export class Post {
@Fields.cuid()
id = ''
@Relations.toMany(() => PostCategory, 'postId')
categories?: PostCategory[]
}
@Entity('categories')
export class Category {
@Fields.cuid()
id = ''
}
@Entity<PostCategory>('posts_categories')
export class PostCategory {
@Fields.string({ required: true })
postId = ''
@Fields.string({ required: true })
categoryId = ''
@Relations.toOne<PostCategory, Category>(() => Category, 'categoryId')
category?: Category
@Relations.toOne<PostCategory, Post>(() => Post, 'postId')
post?: Post
} What is correct way to update post categories in edit form? Delete all and insert new? const post = await repo.update(id, data)
const postCategories = repo.relations(post).categories
await postCategories.deleteMany({ where: { postId: id } })
await postCategories.insert(categories.map(categoryId => ({ categoryId }))) |
Beta Was this translation helpful? Give feedback.
Answered by
noam-honig
Apr 26, 2024
Replies: 1 comment
-
That's one option. Here's a some code that I've writen a while back to do that in the https://github.com/remult/crm-demo/blob/master/src/Deals/Deal.entity.ts#L104 |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
Darkside73
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
That's one option.
Another is to work a little harder to figure out which categories already exist, remove only the ones that are no longer needed and insert ones that are new
Here's a some code that I've writen a while back to do that in the
crm-demo
(we didn't havedeleteMany
back then)https://github.com/remult/crm-demo/blob/master/src/Deals/Deal.entity.ts#L104