Skip to content

Instantly share code, notes, and snippets.

@atultw
Created March 15, 2021 02:32
Show Gist options
  • Save atultw/2ca55fa53d13f3a327912d5cb28a67bf to your computer and use it in GitHub Desktop.
Save atultw/2ca55fa53d13f3a327912d5cb28a67bf to your computer and use it in GitHub Desktop.
Sequelize Many to Many
// sqlconnection is sequelize, connected properly.
class Post extends Model {
}
Post.init({
name: DataTypes.STRING,
description: DataTypes.STRING
}, {
sequelize: sqlconnection,
modelName: 'Post'
})
class Tag extends Model {
}
Tag.init({
name: DataTypes.STRING,
description: DataTypes.STRING
}, {
sequelize: sqlconnection,
modelName: 'Tag'
})
// relationships
Tag.belongsToMany(Post, {
through: {
model: 'PostTags'
}
})
Post.belongsToMany(Tag, {
through: {
model: 'PostTags'
}
})
// actually saving to db
Tag.create({
name: "Photography",
description: "tag for photo related things."
})
Post.create({
name: "a photo",
description: "a description",
Tags: [{name: 'Photography'}]
}, {
include: [ Tag ]
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment