Created Tag, PostTag model & associations
This commit is contained in:
@@ -21,11 +21,19 @@ module.exports = (sequelize, DataTypes) => {
|
|||||||
userId: {
|
userId: {
|
||||||
type: DataTypes.UUID,
|
type: DataTypes.UUID,
|
||||||
allowNull: false,
|
allowNull: false,
|
||||||
},
|
},
|
||||||
}, {
|
}, {
|
||||||
tableName: 'posts',
|
tableName: 'posts',
|
||||||
timestamps: true,
|
timestamps: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Post.associate = (models) => {
|
||||||
|
Post.belongsToMany(models.Tag, {
|
||||||
|
through: models.PostTag,
|
||||||
|
foreignKey: 'postId',
|
||||||
|
otherKey: 'tagId',
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
return Post;
|
return Post;
|
||||||
}
|
};
|
||||||
30
server/models/PostTag.js
Normal file
30
server/models/PostTag.js
Normal 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
28
server/models/Tag.js
Normal 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;
|
||||||
|
};
|
||||||
Reference in New Issue
Block a user