Created Tag, PostTag model & associations

This commit is contained in:
Rykkel
2024-08-11 19:32:05 +08:00
parent b3ee7b4859
commit 82fe2c4940
3 changed files with 69 additions and 3 deletions

View File

@@ -21,11 +21,19 @@ module.exports = (sequelize, DataTypes) => {
userId: {
type: DataTypes.UUID,
allowNull: false,
},
},
}, {
tableName: 'posts',
timestamps: true,
});
Post.associate = (models) => {
Post.belongsToMany(models.Tag, {
through: models.PostTag,
foreignKey: 'postId',
otherKey: 'tagId',
});
};
return Post;
}
};

30
server/models/PostTag.js Normal file
View File

@@ -0,0 +1,30 @@
// handle the relationship between Post and Tag
// Purely join table
module.exports = (sequelize, DataTypes) => {
const PostTag = sequelize.define("PostTag", {
postId: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'posts', // refers to table name
key: 'id'
},
onDelete: 'CASCADE',
},
tagId: {
type: DataTypes.UUID,
allowNull: false,
references: {
model: 'tags', // refers to table name
key: 'id'
},
onDelete: 'CASCADE',
},
}, {
tableName: 'post_tags',
timestamps: false,
});
return PostTag;
};

28
server/models/Tag.js Normal file
View File

@@ -0,0 +1,28 @@
module.exports = (sequelize, DataTypes) => {
const Tag = sequelize.define("Tag", {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
allowNull: false,
primaryKey: true,
},
tag: {
type: DataTypes.STRING(30),
allowNull: false,
unique: true, // Ensure tags are unique
},
}, {
tableName: 'tags',
timestamps: false,
});
Tag.associate = (models) => {
Tag.belongsToMany(models.Post, {
through: models.PostTag,
foreignKey: 'tagId',
otherKey: 'postId',
});
};
return Tag;
};