Guest User

Untitled

a guest
Jul 22nd, 2018
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.07 KB | None | 0 0
  1. // Sequelize (pg)
  2. // Модель Group
  3. module.exports = (sequelize, DataTypes) => {
  4. const Group = sequelize.define('Group', {
  5. name: {
  6. type: DataTypes.STRING,
  7. unique: true,
  8. },
  9. }, {});
  10. Group.associate = function (models) {
  11. Group.belongsToMany(models.Lesson, { through: 'GroupLesson' });
  12. };
  13. return Group;
  14. };
  15. // Модель Lesson
  16. module.exports = (sequelize, DataTypes) => {
  17. const Lesson = sequelize.define('Lesson', {
  18. day: DataTypes.NUMERIC(2),
  19. }, {});
  20. Lesson.associate = function(models) {
  21. Lesson.belongsTo(models.Audience); // простые модели, со строками name
  22. Lesson.belongsTo(models.Teacher);
  23. Lesson.belongsTo(models.Discipline);
  24. Lesson.belongsTo(models.LessonTime);
  25. Lesson.belongsToMany(models.Group, { through: 'GroupLesson' });
  26. };
  27. return Lesson;
  28. };
  29.  
  30. /* Пытаюсь получить JSON со всеми Lesson для данной Group. */
  31.  
  32. Group.find({
  33. where: {
  34. id: req.params.id, // express stuff
  35. },
  36. attributes: ['name'],
  37. include: [{
  38. association: 'Lessons',
  39. attributes: ['day'],
  40. include: ['Teacher', 'Audience', 'Discipline', 'Groups']
  41. }],
  42. })
  43. .then(r => {
  44. res.json(r); // express stuff
  45. });
  46. });
  47.  
  48. /* Но в данных есть лишние данные от ассоциации many-to-many: */
  49.  
  50. {
  51. "name": "SAMPLE",
  52. "Lessons": [{
  53. "day": "1",
  54. "Teacher": {
  55. "id": 1,
  56. "name": "SAMPLE"
  57. },
  58. "Audience": {
  59. "id": 1,
  60. "name": "SAMPLE"
  61. },
  62. "Discipline": {
  63. "id": 1,
  64. "name": "SAMPLE"
  65. },
  66. "Groups": [{
  67. "id": 1,
  68. "name": "SAMPLE",
  69. "GroupLesson": { // <- лишний объект
  70. "GroupId": 1,
  71. "LessonId": 1
  72. }
  73. }],
  74. "GroupLesson": { // <- лишний объект
  75. "GroupId": 1,
  76. "LessonId": 1
  77. }
  78. }]
  79. }
  80.  
  81. /* Как избавиться от лишних объектов? */
Add Comment
Please, Sign In to add comment