include.test.js 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. 'use strict';
  2. const omit = require('lodash/omit');
  3. const chai = require('chai');
  4. const expect = chai.expect;
  5. const Support = require('./support');
  6. const { and, DataTypes, or, Sequelize } = require('@sequelize/core');
  7. const dialect = Support.getTestDialect();
  8. const current = Support.sequelize;
  9. const promiseProps = require('p-props');
  10. function sortById(a, b) {
  11. return a.id < b.id ? -1 : 1;
  12. }
  13. describe(Support.getTestDialectTeaser('Include'), () => {
  14. describe('find', () => {
  15. it('supports a model+alias includeable', async function () {
  16. const Company = this.sequelize.define('Company', {});
  17. const User = this.sequelize.define('User', {});
  18. User.belongsTo(Company, { as: 'Employer' });
  19. await this.sequelize.sync({ force: true });
  20. await User.create();
  21. const user = await User.findOne({
  22. include: [{ model: Company, as: 'Employer' }],
  23. });
  24. expect(user).to.be.ok;
  25. });
  26. it('supports an alias includeable', async function () {
  27. const Company = this.sequelize.define('Company', {});
  28. const User = this.sequelize.define('User', {});
  29. User.belongsTo(Company, { as: 'Employer' });
  30. await this.sequelize.sync({ force: true });
  31. await User.create();
  32. const user = await User.findOne({
  33. include: [{ as: 'Employer' }],
  34. });
  35. expect(user).to.be.ok;
  36. });
  37. it('supports a model includeable if only one association has the model as its target', async function () {
  38. const Company = this.sequelize.define('Company', {});
  39. const User = this.sequelize.define('User', {});
  40. User.belongsTo(Company, { as: 'Employer' });
  41. await this.sequelize.sync({ force: true });
  42. await User.create();
  43. const user = await User.findOne({
  44. include: [Company],
  45. });
  46. expect(user).to.be.ok;
  47. });
  48. it('rejects a model includeable if more than one association has the model as its target', async function () {
  49. const Company = this.sequelize.define('Company', {});
  50. const User = this.sequelize.define('User', {});
  51. User.belongsTo(Company, { as: 'Employer' });
  52. User.belongsTo(Company, { as: 'SecondaryEmployer' });
  53. await expect(User.findOne({ include: [Company] })).to.be.rejectedWith(
  54. `
  55. Ambiguous Include received:
  56. You're trying to include the model "Company", but is associated to "User" multiple times.
  57. Instead of specifying a Model, either:
  58. 1. pass one of the Association object (available in "User.associations") in the "association" option, e.g.:
  59. include: {
  60. association: User.associations.Employer,
  61. },
  62. 2. pass the name of one of the associations in the "association" option, e.g.:
  63. include: {
  64. association: 'Employer',
  65. },
  66. `.trim(),
  67. );
  68. });
  69. it('supports a belongsTo association reference includeable', async function () {
  70. const Company = this.sequelize.define('Company', {});
  71. const User = this.sequelize.define('User', {});
  72. const Employer = User.belongsTo(Company, { as: 'Employer' });
  73. await this.sequelize.sync({ force: true });
  74. await User.create();
  75. const user = await User.findOne({
  76. include: [Employer],
  77. });
  78. expect(user).to.be.ok;
  79. });
  80. it('should support to use associations with Sequelize.col', async function () {
  81. const Table1 = this.sequelize.define('Table1');
  82. const Table2 = this.sequelize.define('Table2');
  83. const Table3 = this.sequelize.define('Table3', { value: DataTypes.INTEGER });
  84. Table1.hasOne(Table2, { foreignKey: 'Table1Id' });
  85. Table2.hasMany(Table3, { as: 'Tables3', foreignKey: 'Table2Id' });
  86. await this.sequelize.sync({ force: true });
  87. const table1 = await Table1.create();
  88. const table2 = await Table2.create({
  89. Table1Id: table1.get('id'),
  90. });
  91. await Table3.bulkCreate(
  92. [
  93. {
  94. Table2Id: table2.get('id'),
  95. value: 5,
  96. },
  97. {
  98. Table2Id: table2.get('id'),
  99. value: 7,
  100. },
  101. ],
  102. {
  103. validate: true,
  104. },
  105. );
  106. const result = await Table1.findAll({
  107. raw: true,
  108. attributes: [[Sequelize.fn('SUM', Sequelize.col('table2.Tables3.value')), 'sum']],
  109. include: [
  110. {
  111. model: Table2,
  112. attributes: [],
  113. include: [
  114. {
  115. model: Table3,
  116. as: 'Tables3',
  117. attributes: [],
  118. },
  119. ],
  120. },
  121. ],
  122. });
  123. expect(result.length).to.equal(1);
  124. expect(Number.parseInt(result[0].sum, 10)).to.eq(12);
  125. });
  126. it('should support a belongsTo association reference with a where', async function () {
  127. const Company = this.sequelize.define('Company', { name: DataTypes.STRING });
  128. const User = this.sequelize.define('User', {});
  129. const Employer = User.belongsTo(Company, { as: 'Employer', foreignKey: 'employerId' });
  130. await this.sequelize.sync({ force: true });
  131. const company = await Company.create({
  132. name: 'CyberCorp',
  133. });
  134. await User.create({
  135. employerId: company.get('id'),
  136. });
  137. const user = await User.findOne({
  138. include: [{ association: Employer, where: { name: 'CyberCorp' } }],
  139. });
  140. expect(user).to.be.ok;
  141. });
  142. it('should support a empty hasOne include', async function () {
  143. const Company = this.sequelize.define('Company', {});
  144. const Person = this.sequelize.define('Person', {});
  145. Company.hasOne(Person, { as: 'CEO' });
  146. await this.sequelize.sync({ force: true });
  147. await Company.create();
  148. const company = await Company.findOne({
  149. include: [{ model: Person, as: 'CEO' }],
  150. });
  151. expect(company).to.be.ok;
  152. });
  153. it('should support a hasOne association reference', async function () {
  154. const Company = this.sequelize.define('Company', {});
  155. const Person = this.sequelize.define('Person', {});
  156. const CEO = Company.hasOne(Person, { as: 'CEO' });
  157. await this.sequelize.sync({ force: true });
  158. await Company.create();
  159. const user = await Company.findOne({
  160. include: [CEO],
  161. });
  162. expect(user).to.be.ok;
  163. });
  164. it('should support including a belongsTo association rather than a model/as pair', async function () {
  165. const Company = this.sequelize.define('Company', {});
  166. const Person = this.sequelize.define('Person', {});
  167. Person.relation = {
  168. Employer: Person.belongsTo(Company, { as: 'employer' }),
  169. };
  170. await this.sequelize.sync({ force: true });
  171. const [person0, company] = await Promise.all([Person.create(), Company.create()]);
  172. await person0.setEmployer(company);
  173. const person = await Person.findOne({
  174. include: [Person.relation.Employer],
  175. });
  176. expect(person).to.be.ok;
  177. expect(person.employer).to.be.ok;
  178. });
  179. it('should support a hasMany association reference', async function () {
  180. const User = this.sequelize.define('user', {});
  181. const Task = this.sequelize.define('task', {});
  182. const Tasks = User.hasMany(Task);
  183. Task.belongsTo(User);
  184. await this.sequelize.sync({ force: true });
  185. const user0 = await User.create();
  186. await user0.createTask();
  187. const user = await User.findOne({
  188. include: [Tasks],
  189. });
  190. expect(user).to.be.ok;
  191. expect(user.tasks).to.be.ok;
  192. });
  193. it('should support a hasMany association reference with a where condition', async function () {
  194. const User = this.sequelize.define('user', {});
  195. const Task = this.sequelize.define('task', { title: DataTypes.STRING });
  196. const Tasks = User.hasMany(Task);
  197. Task.belongsTo(User);
  198. await this.sequelize.sync({ force: true });
  199. const user0 = await User.create();
  200. await Promise.all([
  201. user0.createTask({
  202. title: 'trivial',
  203. }),
  204. user0.createTask({
  205. title: 'pursuit',
  206. }),
  207. ]);
  208. const user = await User.findOne({
  209. include: [{ association: Tasks, where: { title: 'trivial' } }],
  210. });
  211. expect(user).to.be.ok;
  212. expect(user.tasks).to.be.ok;
  213. expect(user.tasks.length).to.equal(1);
  214. });
  215. it('should support a belongsToMany association reference', async function () {
  216. const User = this.sequelize.define('user', {});
  217. const Group = this.sequelize.define('group', {});
  218. const Groups = User.belongsToMany(Group, { through: 'UserGroup' });
  219. Group.belongsToMany(User, { through: 'UserGroup' });
  220. await this.sequelize.sync({ force: true });
  221. const user0 = await User.create();
  222. await user0.createGroup();
  223. const user = await User.findOne({
  224. include: [Groups],
  225. });
  226. expect(user).to.be.ok;
  227. expect(user.groups).to.be.ok;
  228. });
  229. it('should support a simple nested belongsTo -> belongsTo include', async function () {
  230. const Task = this.sequelize.define('Task', {});
  231. const User = this.sequelize.define('User', {});
  232. const Group = this.sequelize.define('Group', {});
  233. Task.belongsTo(User);
  234. User.belongsTo(Group);
  235. await this.sequelize.sync({ force: true });
  236. const props0 = await promiseProps({
  237. task: Task.create(),
  238. user: User.create(),
  239. group: Group.create(),
  240. });
  241. await Promise.all([props0.task.setUser(props0.user), props0.user.setGroup(props0.group)]);
  242. const props = props0;
  243. const task = await Task.findOne({
  244. where: {
  245. id: props.task.id,
  246. },
  247. include: [
  248. {
  249. model: User,
  250. include: [{ model: Group }],
  251. },
  252. ],
  253. });
  254. expect(task.user).to.be.ok;
  255. expect(task.user.group).to.be.ok;
  256. });
  257. it('should support a simple sibling set of belongsTo include', async function () {
  258. const Task = this.sequelize.define('Task', {});
  259. const User = this.sequelize.define('User', {});
  260. const Group = this.sequelize.define('Group', {});
  261. Task.belongsTo(User);
  262. Task.belongsTo(Group);
  263. await this.sequelize.sync({ force: true });
  264. const task0 = await Task.create(
  265. {
  266. user: {},
  267. group: {},
  268. },
  269. {
  270. include: [User, Group],
  271. },
  272. );
  273. const task = await Task.findOne({
  274. where: {
  275. id: task0.id,
  276. },
  277. include: [{ model: User }, { model: Group }],
  278. });
  279. expect(task.user).to.be.ok;
  280. expect(task.group).to.be.ok;
  281. });
  282. it('should support a simple nested hasOne -> hasOne include', async function () {
  283. const Task = this.sequelize.define('Task', {});
  284. const User = this.sequelize.define('User', {});
  285. const Group = this.sequelize.define('Group', {});
  286. User.hasOne(Task);
  287. Group.hasOne(User);
  288. User.belongsTo(Group);
  289. await this.sequelize.sync({ force: true });
  290. const user = await User.create(
  291. {
  292. task: {},
  293. group: {},
  294. },
  295. {
  296. include: [Task, Group],
  297. },
  298. );
  299. const group = await Group.findOne({
  300. where: {
  301. id: user.group.id,
  302. },
  303. include: [
  304. {
  305. model: User,
  306. include: [{ model: Task }],
  307. },
  308. ],
  309. });
  310. expect(group.user).to.be.ok;
  311. expect(group.user.task).to.be.ok;
  312. });
  313. it('should support a simple nested hasMany -> belongsTo include', async function () {
  314. const Task = this.sequelize.define('Task', {});
  315. const User = this.sequelize.define('User', {});
  316. const Project = this.sequelize.define('Project', {});
  317. User.hasMany(Task);
  318. Task.belongsTo(Project);
  319. await this.sequelize.sync({ force: true });
  320. await Project.bulkCreate([{ id: 1 }, { id: 2 }]);
  321. const user0 = await User.create(
  322. {
  323. tasks: [{ projectId: 1 }, { projectId: 2 }, { projectId: 1 }, { projectId: 2 }],
  324. },
  325. {
  326. include: [Task],
  327. },
  328. );
  329. const user = await User.findOne({
  330. where: {
  331. id: user0.id,
  332. },
  333. include: [
  334. {
  335. model: Task,
  336. include: [{ model: Project }],
  337. },
  338. ],
  339. });
  340. expect(user.tasks).to.be.ok;
  341. expect(user.tasks.length).to.equal(4);
  342. for (const task of user.tasks) {
  343. expect(task.project).to.be.ok;
  344. }
  345. });
  346. it('should support a simple nested belongsTo -> hasMany include', async function () {
  347. const Task = this.sequelize.define('Task', {});
  348. const Worker = this.sequelize.define('Worker', {});
  349. const Project = this.sequelize.define('Project', {});
  350. Worker.belongsTo(Project);
  351. Project.hasMany(Worker);
  352. Project.hasMany(Task);
  353. await this.sequelize.sync({ force: true });
  354. const project = await Project.create(
  355. {
  356. workers: [{}],
  357. tasks: [{}, {}, {}, {}],
  358. },
  359. {
  360. include: [Worker, Task],
  361. },
  362. );
  363. const worker = await Worker.findOne({
  364. where: {
  365. id: project.workers[0].id,
  366. },
  367. include: [
  368. {
  369. model: Project,
  370. include: [{ model: Task }],
  371. },
  372. ],
  373. });
  374. expect(worker.project).to.be.ok;
  375. expect(worker.project.tasks).to.be.ok;
  376. expect(worker.project.tasks.length).to.equal(4);
  377. });
  378. it('should support a simple nested hasMany to hasMany include', async function () {
  379. const User = this.sequelize.define('User', {});
  380. const Product = this.sequelize.define('Product', {
  381. title: DataTypes.STRING,
  382. });
  383. const Tag = this.sequelize.define('Tag', {
  384. name: DataTypes.STRING,
  385. });
  386. User.hasMany(Product);
  387. Product.belongsToMany(Tag, { through: 'product_tag' });
  388. Tag.belongsToMany(Product, { through: 'product_tag' });
  389. await this.sequelize.sync({ force: true });
  390. const [products, tags] = await Promise.all([
  391. User.create(
  392. {
  393. id: 1,
  394. products: [{ title: 'Chair' }, { title: 'Desk' }, { title: 'Dress' }, { title: 'Bed' }],
  395. },
  396. {
  397. include: [Product],
  398. },
  399. ).then(() => {
  400. return Product.findAll({ order: [['id']] });
  401. }),
  402. Tag.bulkCreate([{ name: 'A' }, { name: 'B' }, { name: 'C' }]).then(() => {
  403. return Tag.findAll({ order: [['id']] });
  404. }),
  405. ]);
  406. await Promise.all([
  407. products[0].setTags([tags[0], tags[2]]),
  408. products[1].setTags([tags[1]]),
  409. products[2].setTags([tags[0], tags[1], tags[2]]),
  410. ]);
  411. const user = await User.findOne({
  412. where: {
  413. id: 1,
  414. },
  415. include: [
  416. {
  417. model: Product,
  418. include: [{ model: Tag }],
  419. },
  420. ],
  421. order: [User.getAttributes().id, [Product, 'id']],
  422. });
  423. expect(user.products.length).to.equal(4);
  424. expect(user.products[0].tags.length).to.equal(2);
  425. expect(user.products[1].tags.length).to.equal(1);
  426. expect(user.products[2].tags.length).to.equal(3);
  427. expect(user.products[3].tags.length).to.equal(0);
  428. });
  429. it('should support an include with multiple different association types', async function () {
  430. const User = this.sequelize.define('User', {});
  431. const Product = this.sequelize.define('Product', {
  432. title: DataTypes.STRING,
  433. });
  434. const Tag = this.sequelize.define('Tag', {
  435. name: DataTypes.STRING,
  436. });
  437. const Price = this.sequelize.define('Price', {
  438. value: DataTypes.FLOAT,
  439. });
  440. const Group = this.sequelize.define('Group', {
  441. name: DataTypes.STRING,
  442. });
  443. const GroupMember = this.sequelize.define('GroupMember', {});
  444. const Rank = this.sequelize.define('Rank', {
  445. name: DataTypes.STRING,
  446. canInvite: {
  447. type: DataTypes.INTEGER,
  448. defaultValue: 0,
  449. },
  450. canRemove: {
  451. type: DataTypes.INTEGER,
  452. defaultValue: 0,
  453. },
  454. });
  455. User.hasMany(Product);
  456. Product.belongsTo(User);
  457. Product.belongsToMany(Tag, { through: 'product_tag' });
  458. Tag.belongsToMany(Product, { through: 'product_tag' });
  459. Product.belongsTo(Tag, { as: 'Category' });
  460. Product.hasMany(Price);
  461. Price.belongsTo(Product);
  462. User.hasMany(GroupMember, { as: 'Memberships' });
  463. GroupMember.belongsTo(User);
  464. GroupMember.belongsTo(Rank);
  465. GroupMember.belongsTo(Group);
  466. Group.hasMany(GroupMember, { as: 'Memberships' });
  467. await this.sequelize.sync({ force: true });
  468. const [product1, product2, user0, tags] = await Promise.all([
  469. Product.create(
  470. {
  471. id: 1,
  472. title: 'Chair',
  473. prices: [{ value: 5 }, { value: 10 }],
  474. },
  475. { include: [Price] },
  476. ),
  477. Product.create(
  478. {
  479. id: 2,
  480. title: 'Desk',
  481. prices: [{ value: 5 }, { value: 10 }, { value: 15 }, { value: 20 }],
  482. },
  483. { include: [Price] },
  484. ),
  485. User.create(
  486. {
  487. id: 1,
  488. Memberships: [
  489. {
  490. id: 1,
  491. group: { name: 'Developers' },
  492. rank: { name: 'Admin', canInvite: 1, canRemove: 1 },
  493. },
  494. {
  495. id: 2,
  496. group: { name: 'Designers' },
  497. rank: { name: 'Member', canInvite: 1, canRemove: 0 },
  498. },
  499. ],
  500. },
  501. {
  502. include: { model: GroupMember, as: 'Memberships', include: [Group, Rank] },
  503. },
  504. ),
  505. Tag.bulkCreate([{ name: 'A' }, { name: 'B' }, { name: 'C' }]).then(() => {
  506. return Tag.findAll();
  507. }),
  508. ]);
  509. await Promise.all([
  510. user0.setProducts([product1, product2]),
  511. product1.setTags([tags[0], tags[2]]),
  512. product2.setTags([tags[1]]),
  513. product1.setCategory(tags[1]),
  514. ]);
  515. const user = await User.findOne({
  516. where: { id: 1 },
  517. include: [
  518. {
  519. model: GroupMember,
  520. as: 'Memberships',
  521. include: [Group, Rank],
  522. },
  523. {
  524. model: Product,
  525. include: [{ model: Tag, as: 'tags' }, { model: Tag, as: 'Category' }, Price],
  526. },
  527. ],
  528. });
  529. user.Memberships.sort(sortById);
  530. expect(user.Memberships.length).to.equal(2);
  531. expect(user.Memberships[0].group.name).to.equal('Developers');
  532. expect(user.Memberships[0].rank.canRemove).to.equal(1);
  533. expect(user.Memberships[1].group.name).to.equal('Designers');
  534. expect(user.Memberships[1].rank.canRemove).to.equal(0);
  535. user.products.sort(sortById);
  536. expect(user.products.length).to.equal(2);
  537. expect(user.products[0].tags.length).to.equal(2);
  538. expect(user.products[1].tags.length).to.equal(1);
  539. expect(user.products[0].Category).to.be.ok;
  540. expect(user.products[1].Category).not.to.be.ok;
  541. expect(user.products[0].prices.length).to.equal(2);
  542. expect(user.products[1].prices.length).to.equal(4);
  543. });
  544. it('should support specifying attributes', async function () {
  545. const Project = this.sequelize.define('Project', {
  546. title: DataTypes.STRING,
  547. });
  548. const Task = this.sequelize.define('Task', {
  549. title: DataTypes.STRING,
  550. description: DataTypes.TEXT,
  551. });
  552. Project.hasMany(Task);
  553. Task.belongsTo(Project);
  554. await this.sequelize.sync({ force: true });
  555. await Task.create(
  556. {
  557. title: 'FooBar',
  558. project: { title: 'BarFoo' },
  559. },
  560. {
  561. include: [Project],
  562. },
  563. );
  564. const tasks = await Task.findAll({
  565. attributes: ['title'],
  566. include: [{ model: Project, attributes: ['title'] }],
  567. });
  568. expect(tasks[0].title).to.equal('FooBar');
  569. expect(tasks[0].project.title).to.equal('BarFoo');
  570. expect(omit(tasks[0].get(), 'project')).to.deep.equal({ title: 'FooBar' });
  571. expect(tasks[0].project.get()).to.deep.equal({ title: 'BarFoo' });
  572. });
  573. it('should support Sequelize.literal and renaming of attributes in included model attributes', async function () {
  574. const Post = this.sequelize.define('Post', {});
  575. const PostComment = this.sequelize.define('PostComment', {
  576. someProperty: DataTypes.VIRTUAL, // Since we specify the AS part as a part of the literal string, not with sequelize syntax, we have to tell sequelize about the field
  577. comment_title: DataTypes.STRING,
  578. });
  579. Post.hasMany(PostComment);
  580. await this.sequelize.sync({ force: true });
  581. const post = await Post.create({});
  582. await post.createPostComment({
  583. comment_title: 'WAT',
  584. });
  585. let findAttributes;
  586. switch (dialect) {
  587. case 'mssql': {
  588. findAttributes = [
  589. Sequelize.literal(
  590. 'CAST(CASE WHEN EXISTS(SELECT 1) THEN 1 ELSE 0 END AS BIT) AS "postComments.someProperty"',
  591. ),
  592. [
  593. Sequelize.literal('CAST(CASE WHEN EXISTS(SELECT 1) THEN 1 ELSE 0 END AS BIT)'),
  594. 'someProperty2',
  595. ],
  596. ];
  597. break;
  598. }
  599. case 'ibmi': {
  600. findAttributes = [
  601. Sequelize.literal('1 AS "postComments.someProperty"'),
  602. [Sequelize.literal('1'), 'someProperty2'],
  603. ];
  604. break;
  605. }
  606. case 'db2': {
  607. findAttributes = [
  608. Sequelize.literal(
  609. 'EXISTS(SELECT 1 FROM SYSIBM.SYSDUMMY1) AS "postComments.someProperty"',
  610. ),
  611. [Sequelize.literal('EXISTS(SELECT 1 FROM SYSIBM.SYSDUMMY1)'), 'someProperty2'],
  612. ];
  613. break;
  614. }
  615. default: {
  616. findAttributes = [
  617. Sequelize.literal('EXISTS(SELECT 1) AS "postComments.someProperty"'),
  618. [Sequelize.literal('EXISTS(SELECT 1)'), 'someProperty2'],
  619. ];
  620. }
  621. }
  622. findAttributes.push(['comment_title', 'commentTitle']);
  623. const posts = await Post.findAll({
  624. include: [
  625. {
  626. model: PostComment,
  627. attributes: findAttributes,
  628. },
  629. ],
  630. });
  631. expect(posts[0].postComments[0].get('someProperty')).to.be.ok;
  632. expect(posts[0].postComments[0].get('someProperty2')).to.be.ok;
  633. expect(posts[0].postComments[0].get('commentTitle')).to.equal('WAT');
  634. });
  635. it('should support self associated hasMany (with through) include', async function () {
  636. const Group = this.sequelize.define('Group', {
  637. name: DataTypes.STRING,
  638. });
  639. Group.belongsToMany(Group, {
  640. through: 'groups_outsourcing_companies',
  641. as: 'OutsourcingCompanies',
  642. inverse: { as: 'OutsourcedCompanies' },
  643. });
  644. await this.sequelize.sync({ force: true });
  645. await Group.bulkCreate([
  646. { name: 'SoccerMoms' },
  647. { name: 'Coca Cola' },
  648. { name: 'Dell' },
  649. { name: 'Pepsi' },
  650. ]);
  651. const groups = await Group.findAll();
  652. await groups[0].setOutsourcingCompanies(groups.slice(1));
  653. const group = await Group.findOne({
  654. where: {
  655. id: groups[0].id,
  656. },
  657. include: [{ model: Group, as: 'OutsourcingCompanies' }],
  658. });
  659. expect(group.OutsourcingCompanies).to.have.length(3);
  660. });
  661. it('should support including date fields, with the correct timeszone', async function () {
  662. const User = this.sequelize.define(
  663. 'user',
  664. {
  665. dateField: DataTypes.DATE,
  666. },
  667. { timestamps: false },
  668. );
  669. const Group = this.sequelize.define(
  670. 'group',
  671. {
  672. dateField: DataTypes.DATE,
  673. },
  674. { timestamps: false },
  675. );
  676. User.belongsToMany(Group, { through: 'group_user' });
  677. Group.belongsToMany(User, { through: 'group_user' });
  678. await this.sequelize.sync({ force: true });
  679. const [user0, group] = await Promise.all([
  680. User.create({ dateField: Date.UTC(2014, 1, 20) }),
  681. Group.create({ dateField: Date.UTC(2014, 1, 20) }),
  682. ]);
  683. await user0.addGroup(group);
  684. const user = await User.findOne({
  685. where: {
  686. id: user0.id,
  687. },
  688. include: [Group],
  689. });
  690. expect(user.dateField.getTime()).to.equal(Date.UTC(2014, 1, 20));
  691. expect(user.groups[0].dateField.getTime()).to.equal(Date.UTC(2014, 1, 20));
  692. });
  693. it('should support include when retrieving associated objects', async function () {
  694. const User = this.sequelize.define('user', {
  695. name: DataTypes.STRING,
  696. });
  697. const Group = this.sequelize.define('group', {
  698. name: DataTypes.STRING,
  699. });
  700. const UserGroup = this.sequelize.define('user_group', {
  701. vip: DataTypes.INTEGER,
  702. });
  703. User.hasMany(Group);
  704. Group.belongsTo(User);
  705. User.belongsToMany(Group, {
  706. through: UserGroup,
  707. as: 'Clubs',
  708. inverse: {
  709. as: 'Members',
  710. },
  711. });
  712. await this.sequelize.sync({ force: true });
  713. const [owner, member, group] = await Promise.all([
  714. User.create({ name: 'Owner' }),
  715. User.create({ name: 'Member' }),
  716. Group.create({ name: 'Group' }),
  717. ]);
  718. await owner.addGroup(group);
  719. await group.addMember(member);
  720. const groups = await owner.getGroups({
  721. include: [
  722. {
  723. model: User,
  724. as: 'Members',
  725. },
  726. ],
  727. });
  728. expect(groups.length).to.equal(1);
  729. expect(groups[0].Members[0].name).to.equal('Member');
  730. });
  731. });
  732. const createUsersAndItems = async function () {
  733. const User = this.sequelize.define('User', {});
  734. const Item = this.sequelize.define('Item', { test: DataTypes.STRING });
  735. User.hasOne(Item);
  736. Item.belongsTo(User);
  737. this.User = User;
  738. this.Item = Item;
  739. await this.sequelize.sync({ force: true });
  740. const [users, items] = await Promise.all([
  741. User.bulkCreate([{}, {}, {}]).then(() => {
  742. return User.findAll();
  743. }),
  744. Item.bulkCreate([{ test: 'abc' }, { test: 'def' }, { test: 'ghi' }]).then(() => {
  745. return Item.findAll();
  746. }),
  747. ]);
  748. return Promise.all([
  749. users[0].setItem(items[0]),
  750. users[1].setItem(items[1]),
  751. users[2].setItem(items[2]),
  752. ]);
  753. };
  754. describe('where', () => {
  755. beforeEach(async function () {
  756. await createUsersAndItems.bind(this)();
  757. });
  758. it('should support and()', async function () {
  759. const result = await this.User.findAll({
  760. include: [{ model: this.Item, where: and({ test: 'def' }) }],
  761. });
  762. expect(result.length).to.eql(1);
  763. expect(result[0].item.test).to.eql('def');
  764. });
  765. it('should support or()', async function () {
  766. await expect(
  767. this.User.findAll({
  768. include: [
  769. {
  770. model: this.Item,
  771. where: or(
  772. {
  773. test: 'def',
  774. },
  775. {
  776. test: 'abc',
  777. },
  778. ),
  779. },
  780. ],
  781. }),
  782. ).to.eventually.have.length(2);
  783. });
  784. });
  785. describe('findAndCountAll', () => {
  786. it('should include associations to findAndCountAll', async function () {
  787. await createUsersAndItems.bind(this)();
  788. const result = await this.User.findAndCountAll({
  789. include: [
  790. {
  791. model: this.Item,
  792. where: {
  793. test: 'def',
  794. },
  795. },
  796. ],
  797. });
  798. expect(result.count).to.eql(1);
  799. expect(result.rows.length).to.eql(1);
  800. expect(result.rows[0].item.test).to.eql('def');
  801. });
  802. });
  803. describe('association getter', () => {
  804. it('should support getting an include on a N:M association getter', async function () {
  805. const Question = this.sequelize.define('Question', {});
  806. const Answer = this.sequelize.define('Answer', {});
  807. const Questionnaire = this.sequelize.define('Questionnaire', {});
  808. Question.belongsToMany(Answer, { through: 'question_answer' });
  809. Answer.belongsToMany(Question, { through: 'question_answer' });
  810. Questionnaire.hasMany(Question);
  811. Question.belongsTo(Questionnaire);
  812. await this.sequelize.sync({ force: true });
  813. const questionnaire = await Questionnaire.create();
  814. await questionnaire.getQuestions({
  815. include: Answer,
  816. });
  817. });
  818. });
  819. describe('right join', () => {
  820. it('should support getting an include with a right join', async function () {
  821. const User = this.sequelize.define('user', {
  822. name: DataTypes.STRING,
  823. });
  824. const Group = this.sequelize.define('group', {
  825. name: DataTypes.STRING,
  826. });
  827. User.hasMany(Group);
  828. Group.belongsTo(User);
  829. await this.sequelize.sync({ force: true });
  830. await Promise.all([
  831. User.create({ name: 'User 1' }),
  832. User.create({ name: 'User 2' }),
  833. User.create({ name: 'User 3' }),
  834. Group.create({ name: 'A Group' }),
  835. ]);
  836. const groups = await Group.findAll({
  837. include: [
  838. {
  839. model: User,
  840. right: true,
  841. },
  842. ],
  843. });
  844. if (current.dialect.supports['RIGHT JOIN']) {
  845. expect(groups.length).to.equal(3);
  846. } else {
  847. expect(groups.length).to.equal(1);
  848. }
  849. });
  850. it('should support getting an include through with a right join', async function () {
  851. const User = this.sequelize.define('user', {
  852. name: DataTypes.STRING,
  853. });
  854. const Group = this.sequelize.define('group', {
  855. name: DataTypes.STRING,
  856. });
  857. const UserGroup = this.sequelize.define('user_group', {
  858. vip: DataTypes.INTEGER,
  859. });
  860. User.hasMany(Group);
  861. Group.belongsTo(User);
  862. User.belongsToMany(Group, {
  863. through: UserGroup,
  864. as: 'Clubs',
  865. foreignKeyConstraints: false,
  866. inverse: {
  867. as: 'Members',
  868. foreignKeyConstraints: false,
  869. },
  870. });
  871. await this.sequelize.sync({ force: true });
  872. const [member1, member2, group1, group2] = await Promise.all([
  873. User.create({ name: 'Member 1' }),
  874. User.create({ name: 'Member 2' }),
  875. Group.create({ name: 'Group 1' }),
  876. Group.create({ name: 'Group 2' }),
  877. ]);
  878. await Promise.all([
  879. group1.addMember(member1),
  880. group1.addMember(member2),
  881. group2.addMember(member1),
  882. ]);
  883. await group2.destroy();
  884. const groups = await Group.findAll({
  885. include: [
  886. {
  887. model: User,
  888. as: 'Members',
  889. right: true,
  890. },
  891. ],
  892. });
  893. if (current.dialect.supports['RIGHT JOIN']) {
  894. expect(groups.length).to.equal(2);
  895. } else {
  896. expect(groups.length).to.equal(1);
  897. }
  898. });
  899. });
  900. describe('nested includes', () => {
  901. beforeEach(async function () {
  902. const Employee = this.sequelize.define('Employee', { name: DataTypes.STRING });
  903. const Team = this.sequelize.define('Team', { name: DataTypes.STRING });
  904. const Clearence = this.sequelize.define('Clearence', { level: DataTypes.INTEGER });
  905. Team.Members = Team.hasMany(Employee, { as: 'members' });
  906. Employee.Clearence = Employee.hasOne(Clearence, {
  907. as: 'clearence',
  908. foreignKey: 'employeeId',
  909. });
  910. Clearence.Employee = Clearence.belongsTo(Employee, {
  911. as: 'employee',
  912. foreignKey: 'employeeId',
  913. });
  914. this.Employee = Employee;
  915. this.Team = Team;
  916. this.Clearence = Clearence;
  917. await this.sequelize.sync({ force: true });
  918. const instances = await Promise.all([
  919. Team.create({ name: 'TeamA' }),
  920. Team.create({ name: 'TeamB' }),
  921. Employee.create({ name: 'John' }),
  922. Employee.create({ name: 'Jane' }),
  923. Employee.create({ name: 'Josh' }),
  924. Employee.create({ name: 'Jill' }),
  925. Clearence.create({ level: 3 }),
  926. Clearence.create({ level: 5 }),
  927. ]);
  928. await Promise.all([
  929. instances[0].addMembers([instances[2], instances[3]]),
  930. instances[1].addMembers([instances[4], instances[5]]),
  931. instances[2].setClearence(instances[6]),
  932. instances[3].setClearence(instances[7]),
  933. ]);
  934. });
  935. it('should not ripple grandchild required to top level find when required of child is set to false', async function () {
  936. const teams = await this.Team.findAll({
  937. include: [
  938. {
  939. association: this.Team.Members,
  940. required: false,
  941. include: [
  942. {
  943. association: this.Employee.Clearence,
  944. required: true,
  945. },
  946. ],
  947. },
  948. ],
  949. });
  950. expect(teams).to.have.length(2);
  951. });
  952. it('should support eager loading associations using the name of the relation (string)', async function () {
  953. const team = await this.Team.findOne({
  954. where: {
  955. name: 'TeamA',
  956. },
  957. include: [
  958. {
  959. association: 'members',
  960. required: true,
  961. },
  962. ],
  963. });
  964. expect(team.members).to.have.length(2);
  965. });
  966. it('should not ripple grandchild required to top level find when required of child is not given (implicitly false)', async function () {
  967. const teams = await this.Team.findAll({
  968. include: [
  969. {
  970. association: this.Team.Members,
  971. include: [
  972. {
  973. association: this.Employee.Clearence,
  974. required: true,
  975. },
  976. ],
  977. },
  978. ],
  979. });
  980. expect(teams).to.have.length(2);
  981. });
  982. it('should ripple grandchild required to top level find when required of child is set to true as well', async function () {
  983. const teams = await this.Team.findAll({
  984. include: [
  985. {
  986. association: this.Team.Members,
  987. required: true,
  988. include: [
  989. {
  990. association: this.Employee.Clearence,
  991. required: true,
  992. },
  993. ],
  994. },
  995. ],
  996. });
  997. expect(teams).to.have.length(1);
  998. });
  999. });
  1000. });