Skip to content

Instantly share code, notes, and snippets.

@DesignByOnyx
Created September 21, 2019 17:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DesignByOnyx/50a50d9bf9c5207a4184274e1131a922 to your computer and use it in GitHub Desktop.
Save DesignByOnyx/50a50d9bf9c5207a4184274e1131a922 to your computer and use it in GitHub Desktop.
const { tags, ...blogPost } = {
"id": 1, // Notice the blog post has an "id" since we are updating an existing post
"title": "My first blog post",
"body": "...",
"tags": [
{ "id": 1, "text": "sequelize" }, // the existing tag has an "id"
{ "text": "postgres" } // the new tag does not have an "id"
]
};
if (blogPost.id) {
// Update existing blog post
const updatedPost = db.update('blog_posts', blogPost);
Object.assign(blogPost, updatedPost);
// Delete any existing mappings
db.deleteWhere('blog_post_tags', { blog_post_id: blogPost.id });
} else {
// Create new blog post
const newPost = db.create('blog_posts', blogPost);
Object.assign(blogPost, newPost);
}
const existingTags = tags.filter(tag => tag.id !== undefined);
const newTags = db.createMany('tags', tags.filter(tag => tag.id === undefined));
const allTags = existingTags.concat(newTags);
const blogPostTags = allTags.map(tag => {
return {
tag_id: tag.id,
blog_post_id: blogPost.id
};
});
db.createMany('blog_post_tags', blogPostTags);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment