thread.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. let slug = require('slug')
  2. module.exports = (sequelize, DataTypes) => {
  3. let Thread = sequelize.define('Thread', {
  4. name: {
  5. type: DataTypes.TEXT,
  6. set (val) {
  7. this.setDataValue('name', val)
  8. this.setDataValue('slug', slug(val).toLowerCase())
  9. }
  10. },
  11. slug: DataTypes.TEXT,
  12. postsCount: {
  13. type: DataTypes.INTEGER,
  14. defaultValue: 0
  15. }
  16. }, {
  17. classMethods: {
  18. associate (models) {
  19. Thread.belongsTo(models.User)
  20. Thread.belongsTo(models.Category)
  21. Thread.hasMany(models.Post)
  22. },
  23. includeOptions (from, limit) {
  24. let models = sequelize.models
  25. return [
  26. { model: models.User, attributes: ['username', 'createdAt', 'color', 'updatedAt', 'id'] },
  27. models.Category,
  28. {
  29. model: models.Post,
  30. where: { postNumber: { $gte: from } },
  31. order: [['id', 'ASC']],
  32. limit,
  33. include: [
  34. { model: models.Thread, attributes: ['slug'] },
  35. { model: models.User, as: 'Likes', attributes: ['username', 'createdAt', 'id', 'color'] },
  36. { model: models.User, attributes: ['username', 'createdAt', 'id', 'color'] },
  37. {
  38. model: models.Post, as: 'Replies', include:
  39. [{ model: models.User, attributes: ['username', 'id', 'color'] }]
  40. }
  41. ]
  42. }
  43. ]
  44. }
  45. }
  46. })
  47. return Thread
  48. }