Skip to content

Instantly share code, notes, and snippets.

@DesignByOnyx
Last active September 21, 2019 17:28
Show Gist options
  • Save DesignByOnyx/112423ff1625b0758867f75efd72264d to your computer and use it in GitHub Desktop.
Save DesignByOnyx/112423ff1625b0758867f75efd72264d to your computer and use it in GitHub Desktop.
const { tags, ...blogPost } = {
"title": "My second blog post",
"body": "...",
"tags": [
{ "id": 1, "text": "sequelize" }, // the existing tag has an "id"
{ "text": "database" } // the new tag does not have an "id"
]
};
const newPost = db.create('blog_posts', blogPost);
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: newPost.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