Just to add to the many excellent answers in this thread, I find that, as a rule, when one entity refers to another, I want to create a reference entity if (and only if) it does not already exist. For this, I like to use findOrCreate() .
So, imagine that you are storing articles, and each article can have any number of tags. What you usually want to do is:
- Go through all the tags you need and check if they exist. Create them if they do not already exist.
- Once all the tags have been found or created, create your article.
- Once your article is created, link it to the tags you searched for (or created) in step 1.
For me it looks like this:
const { article, tags } = model.import("./model/article"); let tagging = [ tags.findOrCreate({where: {title: "big"}}), tags.findOrCreate({where: {title: "small"}}), tags.findOrCreate({where: {title: "medium"}}), tags.findOrCreate({where: {title: "xsmall"}}) ]; Promise.all(tagging).then((articleTags)=> { article.create({ title: "Foo", body: "Bar" }).then((articleInstance) => { articleInstance.setTags(articleTags.map((articleTag) => articleTag[0])); }) })
source share