separate.test.js 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. 'use strict';
  2. const chai = require('chai');
  3. const expect = chai.expect;
  4. const Support = require('../../support');
  5. const { DataTypes } = require('@sequelize/core');
  6. const current = Support.sequelize;
  7. describe(Support.getTestDialectTeaser('Model'), () => {
  8. describe('findAll', () => {
  9. describe('separate with limit', () => {
  10. it('should not throw syntax error (union)', async () => {
  11. // #9813 testcase
  12. const Project = current.define('Project', { name: DataTypes.STRING });
  13. const LevelTwo = current.define('LevelTwo', { name: DataTypes.STRING });
  14. const LevelThree = current.define('LevelThree', { type: DataTypes.INTEGER });
  15. Project.hasMany(LevelTwo);
  16. LevelTwo.belongsTo(Project);
  17. LevelTwo.hasMany(LevelThree, { as: 'type_ones' });
  18. LevelTwo.hasMany(LevelThree, { as: 'type_twos' });
  19. LevelThree.belongsTo(LevelTwo);
  20. await current.sync({ force: true });
  21. const [project, level21, level22] = await Promise.all([
  22. Project.create({ name: 'testProject' }),
  23. LevelTwo.create({ name: 'testL21' }),
  24. LevelTwo.create({ name: 'testL22' }),
  25. ]);
  26. await Promise.all([project.addLevelTwo(level21), project.addLevelTwo(level22)]);
  27. // one include case
  28. const projects0 = await Project.findAll({
  29. where: { name: 'testProject' },
  30. include: [
  31. {
  32. model: LevelTwo,
  33. include: [
  34. {
  35. model: LevelThree,
  36. as: 'type_ones',
  37. where: { type: 0 },
  38. separate: true,
  39. limit: 1,
  40. order: [['createdAt', 'DESC']],
  41. },
  42. ],
  43. },
  44. ],
  45. });
  46. expect(projects0).to.have.length(1);
  47. expect(projects0[0].levelTwos).to.have.length(2);
  48. expect(projects0[0].levelTwos[0].type_ones).to.have.length(0);
  49. expect(projects0[0].levelTwos[1].type_ones).to.have.length(0);
  50. // two includes case
  51. const projects = await Project.findAll({
  52. where: { name: 'testProject' },
  53. include: [
  54. {
  55. model: LevelTwo,
  56. include: [
  57. {
  58. model: LevelThree,
  59. as: 'type_ones',
  60. where: { type: 0 },
  61. separate: true,
  62. limit: 1,
  63. order: [['createdAt', 'DESC']],
  64. },
  65. {
  66. model: LevelThree,
  67. as: 'type_twos',
  68. where: { type: 1 },
  69. separate: true,
  70. limit: 1,
  71. order: [['createdAt', 'DESC']],
  72. },
  73. ],
  74. },
  75. ],
  76. });
  77. expect(projects).to.have.length(1);
  78. expect(projects[0].levelTwos).to.have.length(2);
  79. expect(projects[0].levelTwos[0].type_ones).to.have.length(0);
  80. expect(projects[0].levelTwos[1].type_ones).to.have.length(0);
  81. });
  82. });
  83. });
  84. });