Created
March 15, 2021 02:32
-
-
Save atultw/2ca55fa53d13f3a327912d5cb28a67bf to your computer and use it in GitHub Desktop.
Sequelize Many to Many
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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