app2-api/modules/blog/post.model.js
2019-08-20 23:28:48 +02:00

95 lines
2.5 KiB
JavaScript

'use strict';
module.exports = function (sequelize, DataTypes) {
const Post = sequelize.define('Post', {
id: {
type: DataTypes.UUID,
defaultValue: DataTypes.UUIDV4,
primaryKey: true,
},
date: {
type: DataTypes.DATE,
allowNull: false,
defaultValue: DataTypes.NOW
},
image: {
type: DataTypes.STRING,
defaultValue: ""
},
title: {
type: DataTypes.STRING,
allowNull: false
},
content: {
type: DataTypes.TEXT,
allowNull: false
},
link: {
type: DataTypes.STRING,
allowNull: false
},
state: {
type: DataTypes.STRING,
allowNull: false,
defaultValue: 'draft'
},
}, {
tableName: 'posts',
freezeTableName: true,
timestamps: true,
defaultScope: {
where: {
state: 'publish',
},
},
});
Post.associate = function (models) {
Post.Categories = Post.belongsToMany(models.Category, {
as: 'categories',
through: models.PostCategory,
foreignKey: 'postId'
});
//Post.Reactions = Post.hasMany(models.PostReaction, { foreignKey: 'postId' });
//OJO antes de force comentar
// OJO GENERA UN FOREIGN KEY Con eventos y habrá ID de otras entidades que no exitan en la tabla eventos, porque son post o speakers
Post.Multimedias = Post.hasMany(models.Multimedia, {
foreignKey: 'entityId',
as: { singular: 'multimedia', plural: 'multimedias' }
});
Post.Comments = Post.hasMany(models.Comment, {
foreignKey: 'entityId',
as: { singular: 'comment', plural: 'comments' }
});
};
Post.addScope('includeAllStates', () => {
return {
where: {
state: ['publish', 'draft']
},
}
});
Post.addScope('includeMultimedias', () => {
return {
include: [{
model: sequelize.models.Multimedia,
as: { singular: 'multimedia', plural: 'multimedias' },
required: false,
include: [{
model: sequelize.models.MultimediaFile,
as: "multimediaFile"
}]
},
]
}
});
return Post;
};