belongs-to-many.test.js 124 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913
  1. 'use strict';
  2. const chai = require('chai');
  3. const expect = chai.expect;
  4. const Support = require('../support');
  5. const { DataTypes, IsolationLevel, Op, Sequelize, sql } = require('@sequelize/core');
  6. const assert = require('node:assert');
  7. const sinon = require('sinon');
  8. const current = Support.sequelize;
  9. const dialect = Support.getTestDialect();
  10. describe(Support.getTestDialectTeaser('BelongsToMany'), () => {
  11. Support.setResetMode('drop');
  12. describe('getAssociations', () => {
  13. beforeEach(async function () {
  14. this.User = this.sequelize.define('User', { username: DataTypes.STRING });
  15. this.Task = this.sequelize.define('Task', {
  16. title: DataTypes.STRING,
  17. active: DataTypes.BOOLEAN,
  18. });
  19. this.User.belongsToMany(this.Task, { through: 'UserTasks', as: 'Tasks', inverse: 'Users' });
  20. this.Task.belongsToMany(this.User, { through: 'UserTasks', as: 'Users', inverse: 'Tasks' });
  21. await this.sequelize.sync({ force: true });
  22. const [john, task1, task2] = await Promise.all([
  23. this.User.create({ username: 'John' }),
  24. this.Task.create({ title: 'Get rich', active: true }),
  25. this.Task.create({ title: 'Die trying', active: false }),
  26. ]);
  27. this.tasks = [task1, task2];
  28. this.user = john;
  29. return john.setTasks([task1, task2]);
  30. });
  31. if (current.dialect.supports.transactions) {
  32. it('supports transactions', async function () {
  33. const sequelize = await Support.createSingleTransactionalTestSequelizeInstance(
  34. this.sequelize,
  35. );
  36. const Article = sequelize.define('Article', { title: DataTypes.STRING });
  37. const Label = sequelize.define('Label', { text: DataTypes.STRING });
  38. Article.belongsToMany(Label, { through: 'ArticleLabels' });
  39. Label.belongsToMany(Article, { through: 'ArticleLabels' });
  40. await sequelize.sync({ force: true });
  41. const [article, label, t] = await Promise.all([
  42. Article.create({ title: 'foo' }),
  43. Label.create({ text: 'bar' }),
  44. sequelize.startUnmanagedTransaction(),
  45. ]);
  46. try {
  47. await article.setLabels([label], { transaction: t });
  48. const articles0 = await Article.findAll({ transaction: t });
  49. const labels0 = await articles0[0].getLabels();
  50. expect(labels0).to.have.length(0);
  51. const articles = await Article.findAll({ transaction: t });
  52. const labels = await articles[0].getLabels({ transaction: t });
  53. expect(labels).to.have.length(1);
  54. } finally {
  55. await t.rollback();
  56. }
  57. });
  58. }
  59. it('gets all associated objects with all fields', async function () {
  60. const john = await this.User.findOne({ where: { username: 'John' } });
  61. const tasks = await john.getTasks();
  62. for (const attributeName of this.Task.modelDefinition.attributes.keys()) {
  63. expect(tasks[0]).to.have.property(attributeName);
  64. }
  65. });
  66. it('gets all associated objects when no options are passed', async function () {
  67. const john = await this.User.findOne({ where: { username: 'John' } });
  68. const tasks = await john.getTasks();
  69. expect(tasks).to.have.length(2);
  70. });
  71. it('only get objects that fulfill the options', async function () {
  72. const john = await this.User.findOne({ where: { username: 'John' } });
  73. const tasks = await john.getTasks({
  74. where: {
  75. active: true,
  76. },
  77. });
  78. expect(tasks).to.have.length(1);
  79. });
  80. it('supports a where not in', async function () {
  81. const john = await this.User.findOne({
  82. where: {
  83. username: 'John',
  84. },
  85. });
  86. const tasks = await john.getTasks({
  87. where: {
  88. title: {
  89. [Op.not]: ['Get rich'],
  90. },
  91. },
  92. });
  93. expect(tasks).to.have.length(1);
  94. });
  95. it('supports a where not in on the primary key', async function () {
  96. const john = await this.User.findOne({
  97. where: {
  98. username: 'John',
  99. },
  100. });
  101. const tasks = await john.getTasks({
  102. where: {
  103. id: {
  104. [Op.not]: [this.tasks[0].get('id')],
  105. },
  106. },
  107. });
  108. expect(tasks).to.have.length(1);
  109. });
  110. it('only gets objects that fulfill options with a formatted value', async function () {
  111. const john = await this.User.findOne({ where: { username: 'John' } });
  112. const tasks = await john.getTasks({ where: { active: true } });
  113. expect(tasks).to.have.length(1);
  114. });
  115. it('get associated objects with an eager load', async function () {
  116. const john = await this.User.findOne({ where: { username: 'John' }, include: [this.Task] });
  117. expect(john.Tasks).to.have.length(2);
  118. });
  119. it('get associated objects with an eager load with conditions but not required', async function () {
  120. const Label = this.sequelize.define('Label', {
  121. title: DataTypes.STRING,
  122. isActive: DataTypes.BOOLEAN,
  123. });
  124. const Task = this.Task;
  125. const User = this.User;
  126. Task.hasMany(Label, { as: 'Labels' });
  127. Label.belongsTo(Task, { as: 'Tasks' });
  128. await Label.sync({ force: true });
  129. const john = await User.findOne({
  130. where: { username: 'John' },
  131. include: [
  132. {
  133. model: Task,
  134. required: false,
  135. include: [{ model: Label, required: false, where: { isActive: true } }],
  136. },
  137. ],
  138. });
  139. expect(john.Tasks).to.have.length(2);
  140. });
  141. if (current.dialect.supports.schemas) {
  142. it('should support schemas', async function () {
  143. const AcmeUser = this.sequelize
  144. .define('User', {
  145. username: DataTypes.STRING,
  146. })
  147. .withSchema({ schema: 'acme', schemaDelimiter: '_' });
  148. const AcmeProject = this.sequelize
  149. .define('Project', {
  150. title: DataTypes.STRING,
  151. active: DataTypes.BOOLEAN,
  152. })
  153. .withSchema({ schema: 'acme', schemaDelimiter: '_' });
  154. const AcmeProjectUsers = this.sequelize
  155. .define('ProjectUsers', {
  156. status: DataTypes.STRING,
  157. data: DataTypes.INTEGER,
  158. })
  159. .withSchema({ schema: 'acme', schemaDelimiter: '_' });
  160. AcmeUser.belongsToMany(AcmeProject, {
  161. through: AcmeProjectUsers,
  162. as: 'Projects',
  163. inverse: 'Users',
  164. });
  165. AcmeProject.belongsToMany(AcmeUser, {
  166. through: AcmeProjectUsers,
  167. as: 'Users',
  168. inverse: 'Projects',
  169. });
  170. await this.sequelize.createSchema('acme');
  171. await Promise.all([AcmeUser.sync({ force: true }), AcmeProject.sync({ force: true })]);
  172. await AcmeProjectUsers.sync({ force: true });
  173. const u = await AcmeUser.create();
  174. const p = await AcmeProject.create();
  175. await u.addProject(p, { through: { status: 'active', data: 42 } });
  176. const projects = await u.getProjects();
  177. expect(projects).to.have.length(1);
  178. const project = projects[0];
  179. expect(project.UserProject).to.be.ok;
  180. expect(project.status).not.to.exist;
  181. expect(project.UserProject.status).to.equal('active');
  182. await this.sequelize.queryInterface.dropAllTables({ schema: 'acme' });
  183. await this.sequelize.dropSchema('acme');
  184. const schemas = await this.sequelize.queryInterface.listSchemas();
  185. expect(schemas).to.not.include('acme');
  186. });
  187. }
  188. it('supports custom primary keys and foreign keys', async function () {
  189. const User = this.sequelize.define(
  190. 'User',
  191. {
  192. id_user: {
  193. type: DataTypes.UUID,
  194. primaryKey: true,
  195. defaultValue: sql.uuidV4,
  196. allowNull: false,
  197. },
  198. },
  199. {
  200. tableName: 'tbl_user',
  201. },
  202. );
  203. const Group = this.sequelize.define(
  204. 'Group',
  205. {
  206. id_group: {
  207. type: DataTypes.UUID,
  208. allowNull: false,
  209. primaryKey: true,
  210. defaultValue: sql.uuidV4,
  211. },
  212. },
  213. {
  214. tableName: 'tbl_group',
  215. },
  216. );
  217. const User_has_Group = this.sequelize.define(
  218. 'User_has_Group',
  219. {},
  220. {
  221. tableName: 'tbl_user_has_group',
  222. },
  223. );
  224. User.belongsToMany(Group, {
  225. as: 'groups',
  226. through: User_has_Group,
  227. foreignKey: 'id_user',
  228. otherKey: 'id_group',
  229. inverse: { as: 'users' },
  230. });
  231. await this.sequelize.sync({ force: true });
  232. const [user0, group] = await Promise.all([User.create(), Group.create()]);
  233. await user0.addGroup(group);
  234. const user = await User.findOne({
  235. where: {},
  236. });
  237. await user.getGroups();
  238. });
  239. it('supports primary key attributes with different field and attribute names', async function () {
  240. const User = this.sequelize.define(
  241. 'User',
  242. {
  243. userSecondId: {
  244. type: DataTypes.UUID,
  245. allowNull: false,
  246. primaryKey: true,
  247. defaultValue: sql.uuidV4,
  248. field: 'user_id',
  249. },
  250. },
  251. {
  252. tableName: 'tbl_user',
  253. },
  254. );
  255. const Group = this.sequelize.define(
  256. 'Group',
  257. {
  258. groupSecondId: {
  259. type: DataTypes.UUID,
  260. allowNull: false,
  261. primaryKey: true,
  262. defaultValue: sql.uuidV4,
  263. field: 'group_id',
  264. },
  265. },
  266. {
  267. tableName: 'tbl_group',
  268. },
  269. );
  270. const User_has_Group = this.sequelize.define(
  271. 'User_has_Group',
  272. {},
  273. {
  274. tableName: 'tbl_user_has_group',
  275. },
  276. );
  277. User.belongsToMany(Group, { through: User_has_Group, as: 'Groups', inverse: 'Users' });
  278. Group.belongsToMany(User, { through: User_has_Group, as: 'Users', inverse: 'Groups' });
  279. await this.sequelize.sync({ force: true });
  280. const [user0, group] = await Promise.all([User.create(), Group.create()]);
  281. await user0.addGroup(group);
  282. const [user, users] = await Promise.all([
  283. User.findOne({
  284. where: {},
  285. include: [Group],
  286. }),
  287. User.findAll({
  288. include: [Group],
  289. }),
  290. ]);
  291. expect(user.Groups.length).to.equal(1);
  292. expect(user.Groups[0].User_has_Group.userUserSecondId).to.be.ok;
  293. if (dialect === 'db2') {
  294. expect(user.Groups[0].User_has_Group.userUserSecondId).to.deep.equal(user.userSecondId);
  295. } else {
  296. expect(user.Groups[0].User_has_Group.userUserSecondId).to.equal(user.userSecondId);
  297. }
  298. expect(user.Groups[0].User_has_Group.groupGroupSecondId).to.be.ok;
  299. if (dialect === 'db2') {
  300. expect(user.Groups[0].User_has_Group.groupGroupSecondId).to.deep.equal(
  301. user.Groups[0].groupSecondId,
  302. );
  303. } else {
  304. expect(user.Groups[0].User_has_Group.groupGroupSecondId).to.equal(
  305. user.Groups[0].groupSecondId,
  306. );
  307. }
  308. expect(users.length).to.equal(1);
  309. expect(users[0].toJSON()).to.be.eql(user.toJSON());
  310. });
  311. it('supports non primary key attributes for joins (sourceKey only)', async function () {
  312. const User = this.sequelize.define(
  313. 'User',
  314. {
  315. id: {
  316. type: DataTypes.UUID,
  317. allowNull: false,
  318. primaryKey: true,
  319. defaultValue: sql.uuidV4,
  320. field: 'user_id',
  321. },
  322. userSecondId: {
  323. type: DataTypes.UUID,
  324. allowNull: false,
  325. defaultValue: sql.uuidV4,
  326. field: 'user_second_id',
  327. },
  328. },
  329. {
  330. tableName: 'tbl_user',
  331. indexes: [
  332. {
  333. unique: true,
  334. fields: ['user_second_id'],
  335. },
  336. ],
  337. },
  338. );
  339. const Group = this.sequelize.define(
  340. 'Group',
  341. {
  342. id: {
  343. type: DataTypes.UUID,
  344. allowNull: false,
  345. primaryKey: true,
  346. defaultValue: sql.uuidV4,
  347. field: 'group_id',
  348. },
  349. groupSecondId: {
  350. type: DataTypes.UUID,
  351. allowNull: false,
  352. defaultValue: sql.uuidV4,
  353. field: 'group_second_id',
  354. },
  355. },
  356. {
  357. tableName: 'tbl_group',
  358. indexes: [
  359. {
  360. unique: true,
  361. fields: ['group_second_id'],
  362. },
  363. ],
  364. },
  365. );
  366. User.belongsToMany(Group, {
  367. through: 'usergroups',
  368. sourceKey: 'userSecondId',
  369. targetKey: 'groupSecondId',
  370. as: 'Groups',
  371. });
  372. await this.sequelize.sync({ force: true });
  373. const [user1, user2, group1, group2] = await Promise.all([
  374. User.create(),
  375. User.create(),
  376. Group.create(),
  377. Group.create(),
  378. ]);
  379. await Promise.all([user1.addGroup(group1), user2.addGroup(group2)]);
  380. const [users, groups] = await Promise.all([
  381. User.findAll({
  382. where: {},
  383. include: [Group],
  384. }),
  385. Group.findAll({
  386. include: [User],
  387. }),
  388. ]);
  389. // Need to add db2 condition for the same. referred to issue: https://github.com/chaijs/chai/issues/102
  390. expect(users.length).to.equal(2);
  391. expect(users[0].Groups.length).to.equal(1);
  392. expect(users[1].Groups.length).to.equal(1);
  393. expect(users[0].Groups[0].usergroups.userUserSecondId).to.be.ok;
  394. if (dialect === 'db2') {
  395. expect(users[0].Groups[0].usergroups.userUserSecondId).to.deep.equal(users[0].userSecondId);
  396. } else {
  397. expect(users[0].Groups[0].usergroups.userUserSecondId).to.equal(users[0].userSecondId);
  398. }
  399. expect(users[0].Groups[0].usergroups.groupGroupSecondId).to.be.ok;
  400. if (dialect === 'db2') {
  401. expect(users[0].Groups[0].usergroups.groupGroupSecondId).to.deep.equal(
  402. users[0].Groups[0].groupSecondId,
  403. );
  404. } else {
  405. expect(users[0].Groups[0].usergroups.groupGroupSecondId).to.equal(
  406. users[0].Groups[0].groupSecondId,
  407. );
  408. }
  409. expect(users[1].Groups[0].usergroups.userUserSecondId).to.be.ok;
  410. if (dialect === 'db2') {
  411. expect(users[1].Groups[0].usergroups.userUserSecondId).to.deep.equal(users[1].userSecondId);
  412. } else {
  413. expect(users[1].Groups[0].usergroups.userUserSecondId).to.equal(users[1].userSecondId);
  414. }
  415. expect(users[1].Groups[0].usergroups.groupGroupSecondId).to.be.ok;
  416. if (dialect === 'db2') {
  417. expect(users[1].Groups[0].usergroups.groupGroupSecondId).to.deep.equal(
  418. users[1].Groups[0].groupSecondId,
  419. );
  420. } else {
  421. expect(users[1].Groups[0].usergroups.groupGroupSecondId).to.equal(
  422. users[1].Groups[0].groupSecondId,
  423. );
  424. }
  425. expect(groups.length).to.equal(2);
  426. expect(groups[0].users.length).to.equal(1);
  427. expect(groups[1].users.length).to.equal(1);
  428. expect(groups[0].users[0].usergroups.groupGroupSecondId).to.be.ok;
  429. if (dialect === 'db2') {
  430. expect(groups[0].users[0].usergroups.groupGroupSecondId).to.deep.equal(
  431. groups[0].groupSecondId,
  432. );
  433. } else {
  434. expect(groups[0].users[0].usergroups.groupGroupSecondId).to.equal(groups[0].groupSecondId);
  435. }
  436. expect(groups[0].users[0].usergroups.userUserSecondId).to.be.ok;
  437. if (dialect === 'db2') {
  438. expect(groups[0].users[0].usergroups.userUserSecondId).to.deep.equal(
  439. groups[0].users[0].userSecondId,
  440. );
  441. } else {
  442. expect(groups[0].users[0].usergroups.userUserSecondId).to.equal(
  443. groups[0].users[0].userSecondId,
  444. );
  445. }
  446. expect(groups[1].users[0].usergroups.groupGroupSecondId).to.be.ok;
  447. if (dialect === 'db2') {
  448. expect(groups[1].users[0].usergroups.groupGroupSecondId).to.deep.equal(
  449. groups[1].groupSecondId,
  450. );
  451. } else {
  452. expect(groups[1].users[0].usergroups.groupGroupSecondId).to.equal(groups[1].groupSecondId);
  453. }
  454. expect(groups[1].users[0].usergroups.userUserSecondId).to.be.ok;
  455. if (dialect === 'db2') {
  456. expect(groups[1].users[0].usergroups.userUserSecondId).to.deep.equal(
  457. groups[1].users[0].userSecondId,
  458. );
  459. } else {
  460. expect(groups[1].users[0].usergroups.userUserSecondId).to.equal(
  461. groups[1].users[0].userSecondId,
  462. );
  463. }
  464. });
  465. it('supports non primary key attributes for joins (targetKey only)', async function () {
  466. const User = this.sequelize.define(
  467. 'User',
  468. {
  469. id: {
  470. type: DataTypes.UUID,
  471. allowNull: false,
  472. primaryKey: true,
  473. defaultValue: sql.uuidV4,
  474. field: 'user_id',
  475. },
  476. userSecondId: {
  477. type: DataTypes.UUID,
  478. allowNull: false,
  479. defaultValue: sql.uuidV4,
  480. field: 'user_second_id',
  481. },
  482. },
  483. {
  484. tableName: 'tbl_user',
  485. indexes: [
  486. {
  487. unique: true,
  488. fields: ['user_second_id'],
  489. },
  490. ],
  491. },
  492. );
  493. const Group = this.sequelize.define(
  494. 'Group',
  495. {
  496. id: {
  497. type: DataTypes.UUID,
  498. allowNull: false,
  499. primaryKey: true,
  500. defaultValue: sql.uuidV4,
  501. field: 'group_id',
  502. },
  503. },
  504. {
  505. tableName: 'tbl_group',
  506. indexes: [
  507. {
  508. unique: true,
  509. fields: ['group_id'],
  510. },
  511. ],
  512. },
  513. );
  514. User.belongsToMany(Group, { through: 'usergroups', sourceKey: 'userSecondId' });
  515. Group.belongsToMany(User, { through: 'usergroups', targetKey: 'userSecondId' });
  516. await this.sequelize.sync({ force: true });
  517. const [user1, user2, group1, group2] = await Promise.all([
  518. User.create(),
  519. User.create(),
  520. Group.create(),
  521. Group.create(),
  522. ]);
  523. await Promise.all([user1.addGroup(group1), user2.addGroup(group2)]);
  524. const [users, groups] = await Promise.all([
  525. User.findAll({
  526. where: {},
  527. include: [Group],
  528. }),
  529. Group.findAll({
  530. include: [User],
  531. }),
  532. ]);
  533. expect(users.length).to.equal(2);
  534. expect(users[0].groups.length).to.equal(1);
  535. expect(users[1].groups.length).to.equal(1);
  536. expect(users[0].groups[0].usergroups.userUserSecondId).to.be.ok;
  537. if (dialect === 'db2') {
  538. expect(users[0].groups[0].usergroups.userUserSecondId).to.deep.equal(users[0].userSecondId);
  539. } else {
  540. expect(users[0].groups[0].usergroups.userUserSecondId).to.equal(users[0].userSecondId);
  541. }
  542. expect(users[0].groups[0].usergroups.groupId).to.be.ok;
  543. if (dialect === 'db2') {
  544. expect(users[0].groups[0].usergroups.groupId).to.deep.equal(users[0].groups[0].id);
  545. } else {
  546. expect(users[0].groups[0].usergroups.groupId).to.equal(users[0].groups[0].id);
  547. }
  548. expect(users[1].groups[0].usergroups.userUserSecondId).to.be.ok;
  549. if (dialect === 'db2') {
  550. expect(users[1].groups[0].usergroups.userUserSecondId).to.deep.equal(users[1].userSecondId);
  551. } else {
  552. expect(users[1].groups[0].usergroups.userUserSecondId).to.equal(users[1].userSecondId);
  553. }
  554. expect(users[1].groups[0].usergroups.groupId).to.be.ok;
  555. if (dialect === 'db2') {
  556. expect(users[1].groups[0].usergroups.groupId).to.deep.equal(users[1].groups[0].id);
  557. } else {
  558. expect(users[1].groups[0].usergroups.groupId).to.equal(users[1].groups[0].id);
  559. }
  560. expect(groups.length).to.equal(2);
  561. expect(groups[0].users.length).to.equal(1);
  562. expect(groups[1].users.length).to.equal(1);
  563. expect(groups[0].users[0].usergroups.groupId).to.be.ok;
  564. if (dialect === 'db2') {
  565. expect(groups[0].users[0].usergroups.groupId).to.deep.equal(groups[0].id);
  566. } else {
  567. expect(groups[0].users[0].usergroups.groupId).to.equal(groups[0].id);
  568. }
  569. expect(groups[0].users[0].usergroups.userUserSecondId).to.be.ok;
  570. if (dialect === 'db2') {
  571. expect(groups[0].users[0].usergroups.userUserSecondId).to.deep.equal(
  572. groups[0].users[0].userSecondId,
  573. );
  574. } else {
  575. expect(groups[0].users[0].usergroups.userUserSecondId).to.equal(
  576. groups[0].users[0].userSecondId,
  577. );
  578. }
  579. expect(groups[1].users[0].usergroups.groupId).to.be.ok;
  580. if (dialect === 'db2') {
  581. expect(groups[1].users[0].usergroups.groupId).to.deep.equal(groups[1].id);
  582. } else {
  583. expect(groups[1].users[0].usergroups.groupId).to.equal(groups[1].id);
  584. }
  585. expect(groups[1].users[0].usergroups.userUserSecondId).to.be.ok;
  586. if (dialect === 'db2') {
  587. expect(groups[1].users[0].usergroups.userUserSecondId).to.deep.equal(
  588. groups[1].users[0].userSecondId,
  589. );
  590. } else {
  591. expect(groups[1].users[0].usergroups.userUserSecondId).to.equal(
  592. groups[1].users[0].userSecondId,
  593. );
  594. }
  595. });
  596. it('supports non primary key attributes for joins (sourceKey and targetKey)', async function () {
  597. const User = this.sequelize.define(
  598. 'User',
  599. {
  600. id: {
  601. type: DataTypes.UUID,
  602. allowNull: false,
  603. primaryKey: true,
  604. defaultValue: sql.uuidV4,
  605. field: 'user_id',
  606. },
  607. userSecondId: {
  608. type: DataTypes.UUID,
  609. allowNull: false,
  610. defaultValue: sql.uuidV4,
  611. field: 'user_second_id',
  612. },
  613. },
  614. {
  615. tableName: 'tbl_user',
  616. indexes: [
  617. {
  618. unique: true,
  619. fields: ['user_second_id'],
  620. },
  621. ],
  622. },
  623. );
  624. const Group = this.sequelize.define(
  625. 'Group',
  626. {
  627. id: {
  628. type: DataTypes.UUID,
  629. allowNull: false,
  630. primaryKey: true,
  631. defaultValue: sql.uuidV4,
  632. field: 'group_id',
  633. },
  634. groupSecondId: {
  635. type: DataTypes.UUID,
  636. allowNull: false,
  637. defaultValue: sql.uuidV4,
  638. field: 'group_second_id',
  639. },
  640. },
  641. {
  642. tableName: 'tbl_group',
  643. indexes: [
  644. {
  645. unique: true,
  646. fields: ['group_second_id'],
  647. },
  648. ],
  649. },
  650. );
  651. User.belongsToMany(Group, {
  652. through: 'usergroups',
  653. sourceKey: 'userSecondId',
  654. targetKey: 'groupSecondId',
  655. as: 'Groups',
  656. inverse: 'Users',
  657. });
  658. Group.belongsToMany(User, {
  659. through: 'usergroups',
  660. sourceKey: 'groupSecondId',
  661. targetKey: 'userSecondId',
  662. as: 'Users',
  663. inverse: 'Groups',
  664. });
  665. await this.sequelize.sync({ force: true });
  666. const [user1, user2, group1, group2] = await Promise.all([
  667. User.create(),
  668. User.create(),
  669. Group.create(),
  670. Group.create(),
  671. ]);
  672. await Promise.all([user1.addGroup(group1), user2.addGroup(group2)]);
  673. const [users, groups] = await Promise.all([
  674. User.findAll({
  675. where: {},
  676. include: [Group],
  677. }),
  678. Group.findAll({
  679. include: [User],
  680. }),
  681. ]);
  682. expect(users.length).to.equal(2);
  683. expect(users[0].Groups.length).to.equal(1);
  684. expect(users[1].Groups.length).to.equal(1);
  685. expect(users[0].Groups[0].usergroups.userUserSecondId).to.be.ok;
  686. if (dialect === 'db2') {
  687. expect(users[0].Groups[0].usergroups.userUserSecondId).to.deep.equal(users[0].userSecondId);
  688. } else {
  689. expect(users[0].Groups[0].usergroups.userUserSecondId).to.equal(users[0].userSecondId);
  690. }
  691. expect(users[0].Groups[0].usergroups.groupGroupSecondId).to.be.ok;
  692. if (dialect === 'db2') {
  693. expect(users[0].Groups[0].usergroups.groupGroupSecondId).to.deep.equal(
  694. users[0].Groups[0].groupSecondId,
  695. );
  696. } else {
  697. expect(users[0].Groups[0].usergroups.groupGroupSecondId).to.equal(
  698. users[0].Groups[0].groupSecondId,
  699. );
  700. }
  701. expect(users[1].Groups[0].usergroups.userUserSecondId).to.be.ok;
  702. if (dialect === 'db2') {
  703. expect(users[1].Groups[0].usergroups.userUserSecondId).to.deep.equal(users[1].userSecondId);
  704. } else {
  705. expect(users[1].Groups[0].usergroups.userUserSecondId).to.equal(users[1].userSecondId);
  706. }
  707. expect(users[1].Groups[0].usergroups.groupGroupSecondId).to.be.ok;
  708. if (dialect === 'db2') {
  709. expect(users[1].Groups[0].usergroups.groupGroupSecondId).to.deep.equal(
  710. users[1].Groups[0].groupSecondId,
  711. );
  712. } else {
  713. expect(users[1].Groups[0].usergroups.groupGroupSecondId).to.equal(
  714. users[1].Groups[0].groupSecondId,
  715. );
  716. }
  717. expect(groups.length).to.equal(2);
  718. expect(groups[0].Users.length).to.equal(1);
  719. expect(groups[1].Users.length).to.equal(1);
  720. expect(groups[0].Users[0].usergroups.groupGroupSecondId).to.be.ok;
  721. if (dialect === 'db2') {
  722. expect(groups[0].Users[0].usergroups.groupGroupSecondId).to.deep.equal(
  723. groups[0].groupSecondId,
  724. );
  725. } else {
  726. expect(groups[0].Users[0].usergroups.groupGroupSecondId).to.equal(groups[0].groupSecondId);
  727. }
  728. expect(groups[0].Users[0].usergroups.userUserSecondId).to.be.ok;
  729. if (dialect === 'db2') {
  730. expect(groups[0].Users[0].usergroups.userUserSecondId).to.deep.equal(
  731. groups[0].Users[0].userSecondId,
  732. );
  733. } else {
  734. expect(groups[0].Users[0].usergroups.userUserSecondId).to.equal(
  735. groups[0].Users[0].userSecondId,
  736. );
  737. }
  738. expect(groups[1].Users[0].usergroups.groupGroupSecondId).to.be.ok;
  739. if (dialect === 'db2') {
  740. expect(groups[1].Users[0].usergroups.groupGroupSecondId).to.deep.equal(
  741. groups[1].groupSecondId,
  742. );
  743. } else {
  744. expect(groups[1].Users[0].usergroups.groupGroupSecondId).to.equal(groups[1].groupSecondId);
  745. }
  746. expect(groups[1].Users[0].usergroups.userUserSecondId).to.be.ok;
  747. if (dialect === 'db2') {
  748. expect(groups[1].Users[0].usergroups.userUserSecondId).to.deep.equal(
  749. groups[1].Users[0].userSecondId,
  750. );
  751. } else {
  752. expect(groups[1].Users[0].usergroups.userUserSecondId).to.equal(
  753. groups[1].Users[0].userSecondId,
  754. );
  755. }
  756. });
  757. it('supports non primary key attributes for joins (custom through model)', async function () {
  758. const User = this.sequelize.define(
  759. 'User',
  760. {
  761. id: {
  762. type: DataTypes.UUID,
  763. allowNull: false,
  764. primaryKey: true,
  765. defaultValue: sql.uuidV4,
  766. field: 'user_id',
  767. },
  768. userSecondId: {
  769. type: DataTypes.UUID,
  770. allowNull: false,
  771. defaultValue: sql.uuidV4,
  772. field: 'user_second_id',
  773. },
  774. },
  775. {
  776. tableName: 'tbl_user',
  777. indexes: [
  778. {
  779. unique: true,
  780. fields: ['user_second_id'],
  781. },
  782. ],
  783. },
  784. );
  785. const Group = this.sequelize.define(
  786. 'Group',
  787. {
  788. id: {
  789. type: DataTypes.UUID,
  790. allowNull: false,
  791. primaryKey: true,
  792. defaultValue: sql.uuidV4,
  793. field: 'group_id',
  794. },
  795. groupSecondId: {
  796. type: DataTypes.UUID,
  797. allowNull: false,
  798. defaultValue: sql.uuidV4,
  799. field: 'group_second_id',
  800. },
  801. },
  802. {
  803. tableName: 'tbl_group',
  804. indexes: [
  805. {
  806. unique: true,
  807. fields: ['group_second_id'],
  808. },
  809. ],
  810. },
  811. );
  812. const User_has_Group = this.sequelize.define(
  813. 'User_has_Group',
  814. {},
  815. {
  816. tableName: 'tbl_user_has_group',
  817. indexes: [
  818. {
  819. unique: true,
  820. fields: ['userUserSecondId', 'groupGroupSecondId'],
  821. name: 'UserHasGroup_Second_Unique',
  822. },
  823. ],
  824. },
  825. );
  826. User.belongsToMany(Group, {
  827. through: User_has_Group,
  828. sourceKey: 'userSecondId',
  829. targetKey: 'groupSecondId',
  830. });
  831. await this.sequelize.sync({ force: true });
  832. const [user1, user2, group1, group2] = await Promise.all([
  833. User.create(),
  834. User.create(),
  835. Group.create(),
  836. Group.create(),
  837. ]);
  838. await Promise.all([user1.addGroup(group1), user2.addGroup(group2)]);
  839. const [users, groups] = await Promise.all([
  840. User.findAll({
  841. where: {},
  842. include: [Group],
  843. }),
  844. Group.findAll({
  845. include: [User],
  846. }),
  847. ]);
  848. expect(users.length).to.equal(2);
  849. expect(users[0].groups.length).to.equal(1);
  850. expect(users[1].groups.length).to.equal(1);
  851. expect(users[0].groups[0].User_has_Group.userUserSecondId).to.be.ok;
  852. if (dialect === 'db2') {
  853. expect(users[0].groups[0].User_has_Group.userUserSecondId).to.deep.equal(
  854. users[0].userSecondId,
  855. );
  856. } else {
  857. expect(users[0].groups[0].User_has_Group.userUserSecondId).to.equal(users[0].userSecondId);
  858. }
  859. expect(users[0].groups[0].User_has_Group.groupGroupSecondId).to.be.ok;
  860. if (dialect === 'db2') {
  861. expect(users[0].groups[0].User_has_Group.groupGroupSecondId).to.deep.equal(
  862. users[0].groups[0].groupSecondId,
  863. );
  864. } else {
  865. expect(users[0].groups[0].User_has_Group.groupGroupSecondId).to.equal(
  866. users[0].groups[0].groupSecondId,
  867. );
  868. }
  869. expect(users[1].groups[0].User_has_Group.userUserSecondId).to.be.ok;
  870. if (dialect === 'db2') {
  871. expect(users[1].groups[0].User_has_Group.userUserSecondId).to.deep.equal(
  872. users[1].userSecondId,
  873. );
  874. } else {
  875. expect(users[1].groups[0].User_has_Group.userUserSecondId).to.equal(users[1].userSecondId);
  876. }
  877. expect(users[1].groups[0].User_has_Group.groupGroupSecondId).to.be.ok;
  878. if (dialect === 'db2') {
  879. expect(users[1].groups[0].User_has_Group.groupGroupSecondId).to.deep.equal(
  880. users[1].groups[0].groupSecondId,
  881. );
  882. } else {
  883. expect(users[1].groups[0].User_has_Group.groupGroupSecondId).to.equal(
  884. users[1].groups[0].groupSecondId,
  885. );
  886. }
  887. expect(groups.length).to.equal(2);
  888. expect(groups[0].users.length).to.equal(1);
  889. expect(groups[1].users.length).to.equal(1);
  890. expect(groups[0].users[0].User_has_Group.groupGroupSecondId).to.be.ok;
  891. if (dialect === 'db2') {
  892. expect(groups[0].users[0].User_has_Group.groupGroupSecondId).to.deep.equal(
  893. groups[0].groupSecondId,
  894. );
  895. } else {
  896. expect(groups[0].users[0].User_has_Group.groupGroupSecondId).to.equal(
  897. groups[0].groupSecondId,
  898. );
  899. }
  900. expect(groups[0].users[0].User_has_Group.userUserSecondId).to.be.ok;
  901. if (dialect === 'db2') {
  902. expect(groups[0].users[0].User_has_Group.userUserSecondId).to.deep.equal(
  903. groups[0].users[0].userSecondId,
  904. );
  905. } else {
  906. expect(groups[0].users[0].User_has_Group.userUserSecondId).to.equal(
  907. groups[0].users[0].userSecondId,
  908. );
  909. }
  910. expect(groups[1].users[0].User_has_Group.groupGroupSecondId).to.be.ok;
  911. if (dialect === 'db2') {
  912. expect(groups[1].users[0].User_has_Group.groupGroupSecondId).to.deep.equal(
  913. groups[1].groupSecondId,
  914. );
  915. } else {
  916. expect(groups[1].users[0].User_has_Group.groupGroupSecondId).to.equal(
  917. groups[1].groupSecondId,
  918. );
  919. }
  920. expect(groups[1].users[0].User_has_Group.userUserSecondId).to.be.ok;
  921. if (dialect === 'db2') {
  922. expect(groups[1].users[0].User_has_Group.userUserSecondId).to.deep.equal(
  923. groups[1].users[0].userSecondId,
  924. );
  925. } else {
  926. expect(groups[1].users[0].User_has_Group.userUserSecondId).to.equal(
  927. groups[1].users[0].userSecondId,
  928. );
  929. }
  930. });
  931. it('supports non primary key attributes for joins for getting associations (sourceKey/targetKey)', async function () {
  932. const User = this.sequelize.define(
  933. 'User',
  934. {
  935. userId: {
  936. type: DataTypes.UUID,
  937. allowNull: false,
  938. primaryKey: true,
  939. defaultValue: sql.uuidV4,
  940. },
  941. userSecondId: {
  942. type: DataTypes.UUID,
  943. allowNull: false,
  944. defaultValue: sql.uuidV4,
  945. field: 'user_second_id',
  946. },
  947. },
  948. {
  949. tableName: 'tbl_user',
  950. indexes: [
  951. {
  952. unique: true,
  953. fields: ['user_second_id'],
  954. },
  955. ],
  956. },
  957. );
  958. const Group = this.sequelize.define(
  959. 'Group',
  960. {
  961. groupId: {
  962. type: DataTypes.UUID,
  963. allowNull: false,
  964. primaryKey: true,
  965. defaultValue: sql.uuidV4,
  966. },
  967. groupSecondId: {
  968. type: DataTypes.UUID,
  969. allowNull: false,
  970. defaultValue: sql.uuidV4,
  971. field: 'group_second_id',
  972. },
  973. },
  974. {
  975. tableName: 'tbl_group',
  976. indexes: [
  977. {
  978. unique: true,
  979. fields: ['group_second_id'],
  980. },
  981. ],
  982. },
  983. );
  984. User.belongsToMany(Group, {
  985. through: 'usergroups',
  986. sourceKey: 'userSecondId',
  987. targetKey: 'groupSecondId',
  988. });
  989. Group.belongsToMany(User, {
  990. through: 'usergroups',
  991. sourceKey: 'groupSecondId',
  992. targetKey: 'userSecondId',
  993. });
  994. await this.sequelize.sync({ force: true });
  995. const [user1, user2, group1, group2] = await Promise.all([
  996. User.create(),
  997. User.create(),
  998. Group.create(),
  999. Group.create(),
  1000. ]);
  1001. await Promise.all([user1.addGroup(group1), user2.addGroup(group2)]);
  1002. const [groups1, groups2, users1, users2] = await Promise.all([
  1003. user1.getGroups(),
  1004. user2.getGroups(),
  1005. group1.getUsers(),
  1006. group2.getUsers(),
  1007. ]);
  1008. expect(groups1.length).to.equal(1);
  1009. expect(groups1[0].id).to.equal(group1.id);
  1010. expect(groups2.length).to.equal(1);
  1011. expect(groups2[0].id).to.equal(group2.id);
  1012. expect(users1.length).to.equal(1);
  1013. expect(users1[0].id).to.equal(user1.id);
  1014. expect(users2.length).to.equal(1);
  1015. expect(users2[0].id).to.equal(user2.id);
  1016. });
  1017. it('supports non primary key attributes for joins (custom foreignKey)', async function () {
  1018. const User = this.sequelize.define(
  1019. 'User',
  1020. {
  1021. id: {
  1022. type: DataTypes.UUID,
  1023. allowNull: false,
  1024. primaryKey: true,
  1025. defaultValue: sql.uuidV4,
  1026. field: 'user_id',
  1027. },
  1028. userSecondId: {
  1029. type: DataTypes.UUID,
  1030. allowNull: false,
  1031. defaultValue: sql.uuidV4,
  1032. field: 'user_second_id',
  1033. },
  1034. },
  1035. {
  1036. tableName: 'tbl_user',
  1037. indexes: [
  1038. {
  1039. unique: true,
  1040. fields: ['user_second_id'],
  1041. },
  1042. ],
  1043. },
  1044. );
  1045. const Group = this.sequelize.define(
  1046. 'Group',
  1047. {
  1048. id: {
  1049. type: DataTypes.UUID,
  1050. allowNull: false,
  1051. primaryKey: true,
  1052. defaultValue: sql.uuidV4,
  1053. field: 'group_id',
  1054. },
  1055. groupSecondId: {
  1056. type: DataTypes.UUID,
  1057. allowNull: false,
  1058. defaultValue: sql.uuidV4,
  1059. field: 'group_second_id',
  1060. },
  1061. },
  1062. {
  1063. tableName: 'tbl_group',
  1064. indexes: [
  1065. {
  1066. unique: true,
  1067. fields: ['group_second_id'],
  1068. },
  1069. ],
  1070. },
  1071. );
  1072. User.belongsToMany(Group, {
  1073. through: 'usergroups',
  1074. foreignKey: 'userId2',
  1075. otherKey: 'groupId2',
  1076. sourceKey: 'userSecondId',
  1077. targetKey: 'groupSecondId',
  1078. });
  1079. await this.sequelize.sync({ force: true });
  1080. const [user1, user2, group1, group2] = await Promise.all([
  1081. User.create(),
  1082. User.create(),
  1083. Group.create(),
  1084. Group.create(),
  1085. ]);
  1086. await Promise.all([user1.addGroup(group1), user2.addGroup(group2)]);
  1087. const [users, groups] = await Promise.all([
  1088. User.findAll({
  1089. where: {},
  1090. include: [Group],
  1091. }),
  1092. Group.findAll({
  1093. include: [User],
  1094. }),
  1095. ]);
  1096. expect(users.length).to.equal(2);
  1097. expect(users[0].groups.length).to.equal(1);
  1098. expect(users[1].groups.length).to.equal(1);
  1099. expect(users[0].groups[0].usergroups.userId2).to.be.ok;
  1100. if (dialect === 'db2') {
  1101. expect(users[0].groups[0].usergroups.userId2).to.deep.equal(users[0].userSecondId);
  1102. } else {
  1103. expect(users[0].groups[0].usergroups.userId2).to.equal(users[0].userSecondId);
  1104. }
  1105. expect(users[0].groups[0].usergroups.groupId2).to.be.ok;
  1106. if (dialect === 'db2') {
  1107. expect(users[0].groups[0].usergroups.groupId2).to.deep.equal(
  1108. users[0].groups[0].groupSecondId,
  1109. );
  1110. } else {
  1111. expect(users[0].groups[0].usergroups.groupId2).to.equal(users[0].groups[0].groupSecondId);
  1112. }
  1113. expect(users[1].groups[0].usergroups.userId2).to.be.ok;
  1114. if (dialect === 'db2') {
  1115. expect(users[1].groups[0].usergroups.userId2).to.deep.equal(users[1].userSecondId);
  1116. } else {
  1117. expect(users[1].groups[0].usergroups.userId2).to.equal(users[1].userSecondId);
  1118. }
  1119. expect(users[1].groups[0].usergroups.groupId2).to.be.ok;
  1120. if (dialect === 'db2') {
  1121. expect(users[1].groups[0].usergroups.groupId2).to.deep.equal(
  1122. users[1].groups[0].groupSecondId,
  1123. );
  1124. } else {
  1125. expect(users[1].groups[0].usergroups.groupId2).to.equal(users[1].groups[0].groupSecondId);
  1126. }
  1127. expect(groups.length).to.equal(2);
  1128. expect(groups[0].users.length).to.equal(1);
  1129. expect(groups[1].users.length).to.equal(1);
  1130. expect(groups[0].users[0].usergroups.groupId2).to.be.ok;
  1131. if (dialect === 'db2') {
  1132. expect(groups[0].users[0].usergroups.groupId2).to.deep.equal(groups[0].groupSecondId);
  1133. } else {
  1134. expect(groups[0].users[0].usergroups.groupId2).to.equal(groups[0].groupSecondId);
  1135. }
  1136. expect(groups[0].users[0].usergroups.userId2).to.be.ok;
  1137. if (dialect === 'db2') {
  1138. expect(groups[0].users[0].usergroups.userId2).to.deep.equal(
  1139. groups[0].users[0].userSecondId,
  1140. );
  1141. } else {
  1142. expect(groups[0].users[0].usergroups.userId2).to.equal(groups[0].users[0].userSecondId);
  1143. }
  1144. expect(groups[1].users[0].usergroups.groupId2).to.be.ok;
  1145. if (dialect === 'db2') {
  1146. expect(groups[1].users[0].usergroups.groupId2).to.deep.equal(groups[1].groupSecondId);
  1147. } else {
  1148. expect(groups[1].users[0].usergroups.groupId2).to.equal(groups[1].groupSecondId);
  1149. }
  1150. expect(groups[1].users[0].usergroups.userId2).to.be.ok;
  1151. if (dialect === 'db2') {
  1152. expect(groups[1].users[0].usergroups.userId2).to.deep.equal(
  1153. groups[1].users[0].userSecondId,
  1154. );
  1155. } else {
  1156. expect(groups[1].users[0].usergroups.userId2).to.equal(groups[1].users[0].userSecondId);
  1157. }
  1158. });
  1159. it('supports non primary key attributes for joins (custom foreignKey, custom through model)', async function () {
  1160. const User = this.sequelize.define(
  1161. 'User',
  1162. {
  1163. id: {
  1164. type: DataTypes.UUID,
  1165. allowNull: false,
  1166. primaryKey: true,
  1167. defaultValue: sql.uuidV4,
  1168. field: 'user_id',
  1169. },
  1170. userSecondId: {
  1171. type: DataTypes.UUID,
  1172. allowNull: false,
  1173. defaultValue: sql.uuidV4,
  1174. field: 'user_second_id',
  1175. },
  1176. },
  1177. {
  1178. tableName: 'tbl_user',
  1179. indexes: [
  1180. {
  1181. unique: true,
  1182. fields: ['user_second_id'],
  1183. },
  1184. ],
  1185. },
  1186. );
  1187. const Group = this.sequelize.define(
  1188. 'Group',
  1189. {
  1190. id: {
  1191. type: DataTypes.UUID,
  1192. allowNull: false,
  1193. primaryKey: true,
  1194. defaultValue: sql.uuidV4,
  1195. field: 'group_id',
  1196. },
  1197. groupSecondId: {
  1198. type: DataTypes.UUID,
  1199. allowNull: false,
  1200. defaultValue: sql.uuidV4,
  1201. field: 'group_second_id',
  1202. },
  1203. },
  1204. {
  1205. tableName: 'tbl_group',
  1206. indexes: [
  1207. {
  1208. unique: true,
  1209. fields: ['group_second_id'],
  1210. },
  1211. ],
  1212. },
  1213. );
  1214. const User_has_Group = this.sequelize.define(
  1215. 'User_has_Group',
  1216. {
  1217. userId2: {
  1218. type: DataTypes.UUID,
  1219. allowNull: false,
  1220. field: 'user_id2',
  1221. },
  1222. groupId2: {
  1223. type: DataTypes.UUID,
  1224. allowNull: false,
  1225. field: 'group_id2',
  1226. },
  1227. },
  1228. {
  1229. tableName: 'tbl_user_has_group',
  1230. indexes: [
  1231. {
  1232. unique: true,
  1233. fields: ['user_id2', 'group_id2'],
  1234. },
  1235. ],
  1236. },
  1237. );
  1238. User.belongsToMany(Group, {
  1239. through: User_has_Group,
  1240. foreignKey: 'userId2',
  1241. otherKey: 'groupId2',
  1242. sourceKey: 'userSecondId',
  1243. targetKey: 'groupSecondId',
  1244. });
  1245. await this.sequelize.sync({ force: true });
  1246. const [user1, user2, group1, group2] = await Promise.all([
  1247. User.create(),
  1248. User.create(),
  1249. Group.create(),
  1250. Group.create(),
  1251. ]);
  1252. await Promise.all([user1.addGroup(group1), user2.addGroup(group2)]);
  1253. const [users, groups] = await Promise.all([
  1254. User.findAll({
  1255. where: {},
  1256. include: [Group],
  1257. }),
  1258. Group.findAll({
  1259. include: [User],
  1260. }),
  1261. ]);
  1262. expect(users.length).to.equal(2);
  1263. expect(users[0].groups.length).to.equal(1);
  1264. expect(users[1].groups.length).to.equal(1);
  1265. expect(users[0].groups[0].User_has_Group.userId2).to.be.ok;
  1266. if (dialect === 'db2') {
  1267. expect(users[0].groups[0].User_has_Group.userId2).to.deep.equal(users[0].userSecondId);
  1268. } else {
  1269. expect(users[0].groups[0].User_has_Group.userId2).to.equal(users[0].userSecondId);
  1270. }
  1271. expect(users[0].groups[0].User_has_Group.groupId2).to.be.ok;
  1272. if (dialect === 'db2') {
  1273. expect(users[0].groups[0].User_has_Group.groupId2).to.deep.equal(
  1274. users[0].groups[0].groupSecondId,
  1275. );
  1276. } else {
  1277. expect(users[0].groups[0].User_has_Group.groupId2).to.equal(
  1278. users[0].groups[0].groupSecondId,
  1279. );
  1280. }
  1281. expect(users[1].groups[0].User_has_Group.userId2).to.be.ok;
  1282. if (dialect === 'db2') {
  1283. expect(users[1].groups[0].User_has_Group.userId2).to.deep.equal(users[1].userSecondId);
  1284. } else {
  1285. expect(users[1].groups[0].User_has_Group.userId2).to.equal(users[1].userSecondId);
  1286. }
  1287. expect(users[1].groups[0].User_has_Group.groupId2).to.be.ok;
  1288. if (dialect === 'db2') {
  1289. expect(users[1].groups[0].User_has_Group.groupId2).to.deep.equal(
  1290. users[1].groups[0].groupSecondId,
  1291. );
  1292. } else {
  1293. expect(users[1].groups[0].User_has_Group.groupId2).to.equal(
  1294. users[1].groups[0].groupSecondId,
  1295. );
  1296. }
  1297. expect(groups.length).to.equal(2);
  1298. expect(groups[0].users.length).to.equal(1);
  1299. expect(groups[1].users.length).to.equal(1);
  1300. expect(groups[0].users[0].User_has_Group.groupId2).to.be.ok;
  1301. if (dialect === 'db2') {
  1302. expect(groups[0].users[0].User_has_Group.groupId2).to.deep.equal(groups[0].groupSecondId);
  1303. } else {
  1304. expect(groups[0].users[0].User_has_Group.groupId2).to.equal(groups[0].groupSecondId);
  1305. }
  1306. expect(groups[0].users[0].User_has_Group.userId2).to.be.ok;
  1307. if (dialect === 'db2') {
  1308. expect(groups[0].users[0].User_has_Group.userId2).to.deep.equal(
  1309. groups[0].users[0].userSecondId,
  1310. );
  1311. } else {
  1312. expect(groups[0].users[0].User_has_Group.userId2).to.equal(groups[0].users[0].userSecondId);
  1313. }
  1314. expect(groups[1].users[0].User_has_Group.groupId2).to.be.ok;
  1315. if (dialect === 'db2') {
  1316. expect(groups[1].users[0].User_has_Group.groupId2).to.deep.equal(groups[1].groupSecondId);
  1317. } else {
  1318. expect(groups[1].users[0].User_has_Group.groupId2).to.equal(groups[1].groupSecondId);
  1319. }
  1320. expect(groups[1].users[0].User_has_Group.userId2).to.be.ok;
  1321. if (dialect === 'db2') {
  1322. expect(groups[1].users[0].User_has_Group.userId2).to.deep.equal(
  1323. groups[1].users[0].userSecondId,
  1324. );
  1325. } else {
  1326. expect(groups[1].users[0].User_has_Group.userId2).to.equal(groups[1].users[0].userSecondId);
  1327. }
  1328. });
  1329. it('supports primary key attributes with different field names where parent include is required', async function () {
  1330. const User = this.sequelize.define(
  1331. 'User',
  1332. {
  1333. id: {
  1334. type: DataTypes.UUID,
  1335. allowNull: false,
  1336. primaryKey: true,
  1337. defaultValue: sql.uuidV4,
  1338. field: 'user_id',
  1339. },
  1340. },
  1341. {
  1342. tableName: 'tbl_user',
  1343. },
  1344. );
  1345. const Company = this.sequelize.define(
  1346. 'Company',
  1347. {
  1348. id: {
  1349. type: DataTypes.UUID,
  1350. allowNull: false,
  1351. primaryKey: true,
  1352. defaultValue: sql.uuidV4,
  1353. field: 'company_id',
  1354. },
  1355. },
  1356. {
  1357. tableName: 'tbl_company',
  1358. },
  1359. );
  1360. const Group = this.sequelize.define(
  1361. 'Group',
  1362. {
  1363. id: {
  1364. type: DataTypes.UUID,
  1365. allowNull: false,
  1366. primaryKey: true,
  1367. defaultValue: sql.uuidV4,
  1368. field: 'group_id',
  1369. },
  1370. },
  1371. {
  1372. tableName: 'tbl_group',
  1373. },
  1374. );
  1375. const Company_has_Group = this.sequelize.define(
  1376. 'Company_has_Group',
  1377. {},
  1378. {
  1379. tableName: 'tbl_company_has_group',
  1380. },
  1381. );
  1382. User.belongsTo(Company);
  1383. Company.hasMany(User);
  1384. Company.belongsToMany(Group, { through: Company_has_Group });
  1385. Group.belongsToMany(Company, { through: Company_has_Group });
  1386. await this.sequelize.sync({ force: true });
  1387. const [user, group, company] = await Promise.all([
  1388. User.create(),
  1389. Group.create(),
  1390. Company.create(),
  1391. ]);
  1392. await Promise.all([user.setCompany(company), company.addGroup(group)]);
  1393. await Promise.all([
  1394. User.findOne({
  1395. where: {},
  1396. include: [{ model: Company, include: [Group] }],
  1397. }),
  1398. User.findAll({
  1399. include: [{ model: Company, include: [Group] }],
  1400. }),
  1401. User.findOne({
  1402. where: {},
  1403. include: [{ model: Company, required: true, include: [Group] }],
  1404. }),
  1405. User.findAll({
  1406. include: [{ model: Company, required: true, include: [Group] }],
  1407. }),
  1408. ]);
  1409. });
  1410. });
  1411. describe('hasAssociations', () => {
  1412. beforeEach(function () {
  1413. this.Article = this.sequelize.define('Article', {
  1414. pk: {
  1415. type: DataTypes.INTEGER,
  1416. autoIncrement: true,
  1417. primaryKey: true,
  1418. },
  1419. title: DataTypes.STRING,
  1420. });
  1421. this.Label = this.sequelize.define('Label', {
  1422. sk: {
  1423. type: DataTypes.INTEGER,
  1424. autoIncrement: true,
  1425. primaryKey: true,
  1426. },
  1427. text: DataTypes.STRING,
  1428. });
  1429. this.ArticleLabel = this.sequelize.define('ArticleLabel');
  1430. });
  1431. if (current.dialect.supports.transactions) {
  1432. it('supports transactions', async function () {
  1433. const sequelize = await Support.createSingleTransactionalTestSequelizeInstance(
  1434. this.sequelize,
  1435. );
  1436. const Article = sequelize.define('Article', { title: DataTypes.STRING });
  1437. const Label = sequelize.define('Label', { text: DataTypes.STRING });
  1438. Article.belongsToMany(Label, { through: 'ArticleLabels' });
  1439. Label.belongsToMany(Article, { through: 'ArticleLabels' });
  1440. await sequelize.sync({ force: true });
  1441. const [article, label, t] = await Promise.all([
  1442. Article.create({ title: 'foo' }),
  1443. Label.create({ text: 'bar' }),
  1444. sequelize.startUnmanagedTransaction(),
  1445. ]);
  1446. try {
  1447. await article.setLabels([label], { transaction: t });
  1448. const articles0 = await Article.findAll({ transaction: t });
  1449. const labels0 = await articles0[0].getLabels();
  1450. expect(labels0).to.have.length(0);
  1451. const articles = await Article.findAll({ transaction: t });
  1452. const labels = await articles[0].getLabels({ transaction: t });
  1453. expect(labels).to.have.length(1);
  1454. } finally {
  1455. await t.rollback();
  1456. }
  1457. });
  1458. }
  1459. it('answers false if only some labels have been assigned', async function () {
  1460. this.Article.belongsToMany(this.Label, { through: this.ArticleLabel });
  1461. this.Label.belongsToMany(this.Article, { through: this.ArticleLabel });
  1462. await this.sequelize.sync({ force: true });
  1463. const [article, label1, label2] = await Promise.all([
  1464. this.Article.create({ title: 'Article' }),
  1465. this.Label.create({ text: 'Awesomeness' }),
  1466. this.Label.create({ text: 'Epicness' }),
  1467. ]);
  1468. await article.addLabel(label1);
  1469. const result = await article.hasLabels([label1, label2]);
  1470. expect(result).to.be.false;
  1471. });
  1472. it('answers false if only some labels have been assigned when passing a primary key instead of an object', async function () {
  1473. this.Article.belongsToMany(this.Label, { through: this.ArticleLabel });
  1474. this.Label.belongsToMany(this.Article, { through: this.ArticleLabel });
  1475. await this.sequelize.sync({ force: true });
  1476. const [article, label1, label2] = await Promise.all([
  1477. this.Article.create({ title: 'Article' }),
  1478. this.Label.create({ text: 'Awesomeness' }),
  1479. this.Label.create({ text: 'Epicness' }),
  1480. ]);
  1481. await article.addLabels([label1]);
  1482. const result = await article.hasLabels([
  1483. label1[this.Label.primaryKeyAttribute],
  1484. label2[this.Label.primaryKeyAttribute],
  1485. ]);
  1486. expect(result).to.be.false;
  1487. });
  1488. it('answers true if all label have been assigned', async function () {
  1489. this.Article.belongsToMany(this.Label, { through: this.ArticleLabel });
  1490. this.Label.belongsToMany(this.Article, { through: this.ArticleLabel });
  1491. await this.sequelize.sync({ force: true });
  1492. const [article, label1, label2] = await Promise.all([
  1493. this.Article.create({ title: 'Article' }),
  1494. this.Label.create({ text: 'Awesomeness' }),
  1495. this.Label.create({ text: 'Epicness' }),
  1496. ]);
  1497. await article.setLabels([label1, label2]);
  1498. const result = await article.hasLabels([label1, label2]);
  1499. expect(result).to.be.true;
  1500. });
  1501. it('answers true if all label have been assigned when passing a primary key instead of an object', async function () {
  1502. this.Article.belongsToMany(this.Label, { through: this.ArticleLabel });
  1503. this.Label.belongsToMany(this.Article, { through: this.ArticleLabel });
  1504. await this.sequelize.sync({ force: true });
  1505. const [article, label1, label2] = await Promise.all([
  1506. this.Article.create({ title: 'Article' }),
  1507. this.Label.create({ text: 'Awesomeness' }),
  1508. this.Label.create({ text: 'Epicness' }),
  1509. ]);
  1510. await article.setLabels([label1, label2]);
  1511. const result = await article.hasLabels([
  1512. label1[this.Label.primaryKeyAttribute],
  1513. label2[this.Label.primaryKeyAttribute],
  1514. ]);
  1515. expect(result).to.be.true;
  1516. });
  1517. it('answers true for labels that have been assigned multitple times', async function () {
  1518. this.ArticleLabel = this.sequelize.define('ArticleLabel', {
  1519. id: {
  1520. primaryKey: true,
  1521. type: DataTypes.INTEGER,
  1522. autoIncrement: true,
  1523. },
  1524. relevance: {
  1525. type: DataTypes.FLOAT,
  1526. validate: {
  1527. min: 0,
  1528. max: 1,
  1529. },
  1530. },
  1531. });
  1532. this.Article.belongsToMany(this.Label, {
  1533. through: { model: this.ArticleLabel, unique: false },
  1534. });
  1535. this.Label.belongsToMany(this.Article, {
  1536. through: { model: this.ArticleLabel, unique: false },
  1537. });
  1538. await this.sequelize.sync({ force: true });
  1539. const [article0, label10, label20] = await Promise.all([
  1540. this.Article.create({ title: 'Article' }),
  1541. this.Label.create({ text: 'Awesomeness' }),
  1542. this.Label.create({ text: 'Epicness' }),
  1543. ]);
  1544. const [article, label1, label2] = await Promise.all([
  1545. article0,
  1546. label10,
  1547. label20,
  1548. article0.addLabel(label10, {
  1549. through: { relevance: 1 },
  1550. }),
  1551. article0.addLabel(label20, {
  1552. through: { relevance: 0.54 },
  1553. }),
  1554. article0.addLabel(label20, {
  1555. through: { relevance: 0.99 },
  1556. }),
  1557. ]);
  1558. const result = await article.hasLabels([label1, label2]);
  1559. await expect(result).to.be.true;
  1560. });
  1561. it('answers true for labels that have been assigned multitple times when passing a primary key instead of an object', async function () {
  1562. this.ArticleLabel = this.sequelize.define('ArticleLabel', {
  1563. id: {
  1564. primaryKey: true,
  1565. type: DataTypes.INTEGER,
  1566. autoIncrement: true,
  1567. },
  1568. relevance: {
  1569. type: DataTypes.FLOAT,
  1570. validate: {
  1571. min: 0,
  1572. max: 1,
  1573. },
  1574. },
  1575. });
  1576. this.Article.belongsToMany(this.Label, {
  1577. through: { model: this.ArticleLabel, unique: false },
  1578. });
  1579. this.Label.belongsToMany(this.Article, {
  1580. through: { model: this.ArticleLabel, unique: false },
  1581. });
  1582. await this.sequelize.sync({ force: true });
  1583. const [article0, label10, label20] = await Promise.all([
  1584. this.Article.create({ title: 'Article' }),
  1585. this.Label.create({ text: 'Awesomeness' }),
  1586. this.Label.create({ text: 'Epicness' }),
  1587. ]);
  1588. const [article, label1, label2] = await Promise.all([
  1589. article0,
  1590. label10,
  1591. label20,
  1592. article0.addLabel(label10, {
  1593. through: { relevance: 1 },
  1594. }),
  1595. article0.addLabel(label20, {
  1596. through: { relevance: 0.54 },
  1597. }),
  1598. article0.addLabel(label20, {
  1599. through: { relevance: 0.99 },
  1600. }),
  1601. ]);
  1602. const result = await article.hasLabels([
  1603. label1[this.Label.primaryKeyAttribute],
  1604. label2[this.Label.primaryKeyAttribute],
  1605. ]);
  1606. await expect(result).to.be.true;
  1607. });
  1608. });
  1609. describe('hasAssociations with binary key', () => {
  1610. beforeEach(function () {
  1611. const keyDataType = ['mysql', 'mariadb', 'db2', 'ibmi'].includes(dialect)
  1612. ? 'BINARY(255)'
  1613. : DataTypes.BLOB('tiny');
  1614. this.Article = this.sequelize.define('Article', {
  1615. id: {
  1616. type: keyDataType,
  1617. primaryKey: true,
  1618. },
  1619. });
  1620. this.Label = this.sequelize.define('Label', {
  1621. id: {
  1622. type: keyDataType,
  1623. primaryKey: true,
  1624. },
  1625. });
  1626. this.ArticleLabel = this.sequelize.define('ArticleLabel');
  1627. this.Article.belongsToMany(this.Label, { through: this.ArticleLabel });
  1628. this.Label.belongsToMany(this.Article, { through: this.ArticleLabel });
  1629. return this.sequelize.sync({ force: true });
  1630. });
  1631. // article.hasLabels returns false for db2 despite article has label
  1632. // Problably due to binary id. Hence, disabling it for db2 dialect
  1633. if (dialect !== 'db2') {
  1634. it('answers true for labels that have been assigned', async function () {
  1635. const [article, label] = await Promise.all([
  1636. this.Article.create({
  1637. // note that mariadb appends binary values at the end https://mariadb.com/kb/en/binary/
  1638. id: Buffer.alloc(255),
  1639. }),
  1640. this.Label.create({
  1641. id: Buffer.alloc(255),
  1642. }),
  1643. ]);
  1644. await article.addLabel(label);
  1645. const result = await article.hasLabels([label]);
  1646. await expect(result).to.be.true;
  1647. });
  1648. }
  1649. it('answer false for labels that have not been assigned', async function () {
  1650. const [article, label] = await Promise.all([
  1651. this.Article.create({
  1652. id: Buffer.alloc(255),
  1653. }),
  1654. this.Label.create({
  1655. id: Buffer.alloc(255),
  1656. }),
  1657. ]);
  1658. const result = await article.hasLabels([label]);
  1659. expect(result).to.be.false;
  1660. });
  1661. });
  1662. describe('countAssociations', () => {
  1663. beforeEach(async function () {
  1664. this.User = this.sequelize.define('User', {
  1665. username: DataTypes.STRING,
  1666. });
  1667. this.Task = this.sequelize.define('Task', {
  1668. title: DataTypes.STRING,
  1669. active: DataTypes.BOOLEAN,
  1670. });
  1671. this.UserTask = this.sequelize.define('UserTask', {
  1672. id: {
  1673. type: DataTypes.INTEGER,
  1674. primaryKey: true,
  1675. autoIncrement: true,
  1676. },
  1677. started: {
  1678. type: DataTypes.BOOLEAN,
  1679. defaultValue: false,
  1680. },
  1681. });
  1682. this.User.belongsToMany(this.Task, { through: this.UserTask });
  1683. this.Task.belongsToMany(this.User, { through: this.UserTask });
  1684. await this.sequelize.sync({ force: true });
  1685. const [john, task1, task2] = await Promise.all([
  1686. this.User.create({ username: 'John' }),
  1687. this.Task.create({ title: 'Get rich', active: true }),
  1688. this.Task.create({ title: 'Die trying', active: false }),
  1689. ]);
  1690. this.tasks = [task1, task2];
  1691. this.user = john;
  1692. return john.setTasks([task1, task2]);
  1693. });
  1694. it('should count all associations', async function () {
  1695. expect(await this.user.countTasks({})).to.equal(2);
  1696. });
  1697. it('should count filtered associations', async function () {
  1698. expect(await this.user.countTasks({ where: { active: true } })).to.equal(1);
  1699. });
  1700. it('should count scoped associations', async function () {
  1701. this.User.belongsToMany(this.Task, {
  1702. as: 'activeTasks',
  1703. through: this.UserTask,
  1704. scope: {
  1705. active: true,
  1706. },
  1707. });
  1708. expect(await this.user.countActiveTasks({})).to.equal(1);
  1709. });
  1710. it('should count scoped through associations', async function () {
  1711. this.User.belongsToMany(this.Task, {
  1712. as: 'startedTasks',
  1713. inverse: {
  1714. as: 'startedUsers',
  1715. },
  1716. through: {
  1717. model: this.UserTask,
  1718. scope: {
  1719. started: true,
  1720. },
  1721. },
  1722. });
  1723. for (let i = 0; i < 2; i++) {
  1724. await this.user.addTask(await this.Task.create(), {
  1725. through: { started: true },
  1726. });
  1727. }
  1728. expect(await this.user.countStartedTasks({})).to.equal(2);
  1729. });
  1730. });
  1731. describe('setAssociations', () => {
  1732. it('clears associations when passing null to the set-method', async function () {
  1733. const User = this.sequelize.define('User', { username: DataTypes.STRING });
  1734. const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
  1735. User.belongsToMany(Task, { through: 'UserTasks' });
  1736. Task.belongsToMany(User, { through: 'UserTasks' });
  1737. await this.sequelize.sync({ force: true });
  1738. const [user, task] = await Promise.all([
  1739. User.create({ username: 'foo' }),
  1740. Task.create({ title: 'task' }),
  1741. ]);
  1742. await task.setUsers([user]);
  1743. const _users0 = await task.getUsers();
  1744. expect(_users0).to.have.length(1);
  1745. await task.setUsers(null);
  1746. const _users = await task.getUsers();
  1747. expect(_users).to.have.length(0);
  1748. });
  1749. it('should be able to set twice with custom primary keys', async function () {
  1750. const User = this.sequelize.define('User', {
  1751. uid: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  1752. username: DataTypes.STRING,
  1753. });
  1754. const Task = this.sequelize.define('Task', {
  1755. tid: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  1756. title: DataTypes.STRING,
  1757. });
  1758. User.belongsToMany(Task, { through: 'UserTasks' });
  1759. Task.belongsToMany(User, { through: 'UserTasks' });
  1760. await this.sequelize.sync({ force: true });
  1761. const [user1, user2, task] = await Promise.all([
  1762. User.create({ username: 'foo' }),
  1763. User.create({ username: 'bar' }),
  1764. Task.create({ title: 'task' }),
  1765. ]);
  1766. await task.setUsers([user1]);
  1767. user2.user_has_task = { usertitle: 'Something' };
  1768. await task.setUsers([user1, user2]);
  1769. const _users = await task.getUsers();
  1770. expect(_users).to.have.length(2);
  1771. });
  1772. it('joins an association with custom primary keys', async function () {
  1773. const Group = this.sequelize.define('group', {
  1774. group_id: { type: DataTypes.INTEGER, primaryKey: true },
  1775. name: DataTypes.STRING(64),
  1776. });
  1777. const Member = this.sequelize.define('member', {
  1778. member_id: { type: DataTypes.INTEGER, primaryKey: true },
  1779. email: DataTypes.STRING(64),
  1780. });
  1781. Group.belongsToMany(Member, {
  1782. through: 'group_members',
  1783. foreignKey: 'group_id',
  1784. otherKey: 'member_id',
  1785. });
  1786. Member.belongsToMany(Group, {
  1787. through: 'group_members',
  1788. foreignKey: 'member_id',
  1789. otherKey: 'group_id',
  1790. });
  1791. await this.sequelize.sync({ force: true });
  1792. const [group0, member] = await Promise.all([
  1793. Group.create({ group_id: 1, name: 'Group1' }),
  1794. Member.create({ member_id: 10, email: 'team@sequelizejs.com' }),
  1795. ]);
  1796. await group0.addMember(member);
  1797. const group = group0;
  1798. const members = await group.getMembers();
  1799. expect(members).to.be.instanceof(Array);
  1800. expect(members).to.have.length(1);
  1801. expect(members[0].member_id).to.equal(10);
  1802. expect(members[0].email).to.equal('team@sequelizejs.com');
  1803. });
  1804. it('supports passing the primary key instead of an object', async function () {
  1805. const User = this.sequelize.define('User', { username: DataTypes.STRING });
  1806. const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
  1807. User.belongsToMany(Task, { through: 'UserTasks' });
  1808. Task.belongsToMany(User, { through: 'UserTasks' });
  1809. await this.sequelize.sync({ force: true });
  1810. const [user, task1, task2] = await Promise.all([
  1811. User.create({ id: 12 }),
  1812. Task.create({ id: 50, title: 'get started' }),
  1813. Task.create({ id: 5, title: 'wat' }),
  1814. ]);
  1815. await user.addTask(task1.id);
  1816. await user.setTasks([task2.id]);
  1817. const tasks = await user.getTasks();
  1818. expect(tasks).to.have.length(1);
  1819. expect(tasks[0].title).to.equal('wat');
  1820. });
  1821. it('using scope to set associations', async function () {
  1822. const ItemTag = this.sequelize.define('ItemTag', {
  1823. id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  1824. tag_id: { type: DataTypes.INTEGER, unique: false },
  1825. taggable: { type: DataTypes.STRING },
  1826. taggable_id: { type: DataTypes.INTEGER, unique: false },
  1827. });
  1828. const Tag = this.sequelize.define('Tag', {
  1829. id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  1830. name: DataTypes.STRING,
  1831. });
  1832. const Comment = this.sequelize.define('Comment', {
  1833. id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  1834. name: DataTypes.STRING,
  1835. });
  1836. const Post = this.sequelize.define('Post', {
  1837. id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  1838. name: DataTypes.STRING,
  1839. });
  1840. Post.belongsToMany(Tag, {
  1841. through: { model: ItemTag, unique: false, scope: { taggable: 'post' } },
  1842. foreignKey: 'taggable_id',
  1843. });
  1844. Comment.belongsToMany(Tag, {
  1845. through: { model: ItemTag, unique: false, scope: { taggable: 'comment' } },
  1846. foreignKey: 'taggable_id',
  1847. // taggable_id already references Post, we can't make it reference Comment
  1848. foreignKeyConstraints: false,
  1849. });
  1850. await this.sequelize.sync({ force: true });
  1851. const [post, comment, tag] = await Promise.all([
  1852. Post.create({ name: 'post1' }),
  1853. Comment.create({ name: 'comment1' }),
  1854. Tag.create({ name: 'tag1' }),
  1855. ]);
  1856. this.post = post;
  1857. this.comment = comment;
  1858. this.tag = tag;
  1859. await this.post.setTags([this.tag]);
  1860. await this.comment.setTags([this.tag]);
  1861. const [postTags, commentTags] = await Promise.all([
  1862. this.post.getTags(),
  1863. this.comment.getTags(),
  1864. ]);
  1865. expect(postTags).to.have.length(1);
  1866. expect(commentTags).to.have.length(1);
  1867. });
  1868. it('updating association via set associations with scope', async function () {
  1869. const ItemTag = this.sequelize.define('ItemTag', {
  1870. id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  1871. tag_id: { type: DataTypes.INTEGER, unique: false },
  1872. taggable: { type: DataTypes.STRING },
  1873. taggable_id: { type: DataTypes.INTEGER, unique: false },
  1874. });
  1875. const Tag = this.sequelize.define('Tag', {
  1876. id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  1877. name: DataTypes.STRING,
  1878. });
  1879. const Comment = this.sequelize.define('Comment', {
  1880. id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  1881. name: DataTypes.STRING,
  1882. });
  1883. const Post = this.sequelize.define('Post', {
  1884. id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true },
  1885. name: DataTypes.STRING,
  1886. });
  1887. Post.belongsToMany(Tag, {
  1888. through: { model: ItemTag, unique: false, scope: { taggable: 'post' } },
  1889. foreignKey: 'taggable_id',
  1890. });
  1891. Comment.belongsToMany(Tag, {
  1892. through: { model: ItemTag, unique: false, scope: { taggable: 'comment' } },
  1893. foreignKey: 'taggable_id',
  1894. // taggable_id already references Post, we can't make it reference Comment
  1895. foreignKeyConstraints: false,
  1896. });
  1897. await this.sequelize.sync({ force: true });
  1898. const [post, comment, tag, secondTag] = await Promise.all([
  1899. Post.create({ name: 'post1' }),
  1900. Comment.create({ name: 'comment1' }),
  1901. Tag.create({ name: 'tag1' }),
  1902. Tag.create({ name: 'tag2' }),
  1903. ]);
  1904. await post.setTags([tag, secondTag]);
  1905. await comment.setTags([tag, secondTag]);
  1906. await post.setTags([tag]);
  1907. const [postTags, commentTags] = await Promise.all([post.getTags(), comment.getTags()]);
  1908. expect(postTags).to.have.length(1);
  1909. expect(commentTags).to.have.length(2);
  1910. });
  1911. it('should catch EmptyResultError when rejectOnEmpty is set', async function () {
  1912. const User = this.sequelize.define(
  1913. 'User',
  1914. { username: DataTypes.STRING },
  1915. { rejectOnEmpty: true },
  1916. );
  1917. const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
  1918. User.belongsToMany(Task, { through: 'UserTasks' });
  1919. Task.belongsToMany(User, { through: 'UserTasks' });
  1920. await this.sequelize.sync({ force: true });
  1921. const [user0, task1, task2] = await Promise.all([
  1922. User.create({ id: 12 }),
  1923. Task.create({ id: 50, title: 'get started' }),
  1924. Task.create({ id: 51, title: 'following up' }),
  1925. ]);
  1926. await user0.setTasks([task1, task2]);
  1927. const user = user0;
  1928. const userTasks = await user.getTasks();
  1929. expect(userTasks).to.be.an('array').that.has.a.lengthOf(2);
  1930. expect(userTasks[0]).to.be.an.instanceOf(Task);
  1931. });
  1932. });
  1933. describe('createAssociations', () => {
  1934. it('creates a new associated object', async function () {
  1935. const User = this.sequelize.define('User', { username: DataTypes.STRING });
  1936. const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
  1937. User.belongsToMany(Task, { through: 'UserTasks' });
  1938. Task.belongsToMany(User, { through: 'UserTasks' });
  1939. await this.sequelize.sync({ force: true });
  1940. const task = await Task.create({ title: 'task' });
  1941. const createdUser = await task.createUser({ username: 'foo' });
  1942. expect(createdUser).to.be.instanceof(User);
  1943. expect(createdUser.username).to.equal('foo');
  1944. const _users = await task.getUsers();
  1945. expect(_users).to.have.length(1);
  1946. });
  1947. if (current.dialect.supports.transactions) {
  1948. it('supports transactions', async function () {
  1949. const sequelize = await Support.createSingleTransactionalTestSequelizeInstance(
  1950. this.sequelize,
  1951. );
  1952. const User = sequelize.define('User', { username: DataTypes.STRING });
  1953. const Task = sequelize.define('Task', { title: DataTypes.STRING });
  1954. User.belongsToMany(Task, { through: 'UserTasks' });
  1955. Task.belongsToMany(User, { through: 'UserTasks' });
  1956. await sequelize.sync({ force: true });
  1957. const [task, t] = await Promise.all([
  1958. Task.create({ title: 'task' }),
  1959. sequelize.startUnmanagedTransaction(),
  1960. ]);
  1961. await task.createUser({ username: 'foo' }, { transaction: t });
  1962. const users0 = await task.getUsers();
  1963. expect(users0).to.have.length(0);
  1964. const users = await task.getUsers({ transaction: t });
  1965. expect(users).to.have.length(1);
  1966. await t.rollback();
  1967. });
  1968. }
  1969. it('supports setting through table attributes', async function () {
  1970. const User = this.sequelize.define('user', {});
  1971. const Group = this.sequelize.define('group', {});
  1972. const UserGroups = this.sequelize.define('user_groups', {
  1973. isAdmin: DataTypes.BOOLEAN,
  1974. });
  1975. User.belongsToMany(Group, { through: UserGroups });
  1976. Group.belongsToMany(User, { through: UserGroups });
  1977. await this.sequelize.sync({ force: true });
  1978. const group = await Group.create({});
  1979. await Promise.all([
  1980. group.createUser({ id: 1 }, { through: { isAdmin: true } }),
  1981. group.createUser({ id: 2 }, { through: { isAdmin: false } }),
  1982. ]);
  1983. const userGroups = await UserGroups.findAll();
  1984. userGroups.sort((a, b) => {
  1985. return a.userId < b.userId ? -1 : 1;
  1986. });
  1987. expect(userGroups[0].userId).to.equal(1);
  1988. expect(userGroups[0].isAdmin).to.be.ok;
  1989. expect(userGroups[1].userId).to.equal(2);
  1990. expect(userGroups[1].isAdmin).not.to.be.ok;
  1991. });
  1992. it('supports using the field parameter', async function () {
  1993. const User = this.sequelize.define('User', { username: DataTypes.STRING });
  1994. const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
  1995. User.belongsToMany(Task, { through: 'UserTasks' });
  1996. Task.belongsToMany(User, { through: 'UserTasks' });
  1997. await this.sequelize.sync({ force: true });
  1998. const task = await Task.create({ title: 'task' });
  1999. const createdUser = await task.createUser({ username: 'foo' }, { fields: ['username'] });
  2000. expect(createdUser).to.be.instanceof(User);
  2001. expect(createdUser.username).to.equal('foo');
  2002. const _users = await task.getUsers();
  2003. expect(_users).to.have.length(1);
  2004. });
  2005. });
  2006. describe('addAssociations', () => {
  2007. it('supports both single instance and array', async function () {
  2008. const User = this.sequelize.define('User', { username: DataTypes.STRING });
  2009. const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
  2010. User.belongsToMany(Task, { through: 'UserTasks' });
  2011. Task.belongsToMany(User, { through: 'UserTasks' });
  2012. await this.sequelize.sync({ force: true });
  2013. const [user0, task1, task2] = await Promise.all([
  2014. User.create({ id: 12 }),
  2015. Task.create({ id: 50, title: 'get started' }),
  2016. Task.create({ id: 52, title: 'get done' }),
  2017. ]);
  2018. await Promise.all([user0.addTask(task1), user0.addTask([task2])]);
  2019. const user = user0;
  2020. const tasks = await user.getTasks();
  2021. expect(tasks).to.have.length(2);
  2022. expect(tasks.find(item => item.title === 'get started')).to.be.ok;
  2023. expect(tasks.find(item => item.title === 'get done')).to.be.ok;
  2024. });
  2025. if (current.dialect.supports.transactions) {
  2026. it('supports transactions', async function () {
  2027. const sequelize = await Support.createSingleTransactionalTestSequelizeInstance(
  2028. this.sequelize,
  2029. );
  2030. const User = sequelize.define('User', { username: DataTypes.STRING });
  2031. const Task = sequelize.define('Task', { title: DataTypes.STRING });
  2032. User.belongsToMany(Task, { through: 'UserTasks' });
  2033. Task.belongsToMany(User, { through: 'UserTasks' });
  2034. await sequelize.sync({ force: true });
  2035. const [user, task, t] = await Promise.all([
  2036. User.create({ username: 'foo' }),
  2037. Task.create({ title: 'task' }),
  2038. sequelize.startUnmanagedTransaction(),
  2039. ]);
  2040. await task.addUser(user, { transaction: t });
  2041. const hasUser0 = await task.hasUser(user);
  2042. expect(hasUser0).to.be.false;
  2043. const hasUser = await task.hasUser(user, { transaction: t });
  2044. expect(hasUser).to.be.true;
  2045. await t.rollback();
  2046. });
  2047. it('supports transactions when updating a through model', async function () {
  2048. const sequelize = await Support.createSingleTransactionalTestSequelizeInstance(
  2049. this.sequelize,
  2050. );
  2051. const User = sequelize.define('User', { username: DataTypes.STRING });
  2052. const Task = sequelize.define('Task', { title: DataTypes.STRING });
  2053. const UserTask = sequelize.define('UserTask', {
  2054. status: DataTypes.STRING,
  2055. });
  2056. User.belongsToMany(Task, { through: UserTask, as: 'Tasks', inverse: 'Users' });
  2057. await sequelize.sync({ force: true });
  2058. const [user, task, t] = await Promise.all([
  2059. User.create({ username: 'foo' }),
  2060. Task.create({ title: 'task' }),
  2061. sequelize.startUnmanagedTransaction({ isolationLevel: IsolationLevel.SERIALIZABLE }),
  2062. ]);
  2063. await task.addUser(user, { through: { status: 'pending' } }); // Create without transaction, so the old value is
  2064. // accesible from outside the transaction
  2065. await task.addUser(user, { transaction: t, through: { status: 'completed' } }); // Add an already exisiting user in
  2066. // a transaction, updating a value
  2067. // in the join table
  2068. const [tasks, transactionTasks] = await Promise.all([
  2069. user.getTasks(),
  2070. user.getTasks({ transaction: t }),
  2071. ]);
  2072. expect(tasks[0].UserTask.status).to.equal('pending');
  2073. expect(transactionTasks[0].UserTask.status).to.equal('completed');
  2074. await t.rollback();
  2075. });
  2076. }
  2077. it('supports passing the primary key instead of an object', async function () {
  2078. const User = this.sequelize.define('User', { username: DataTypes.STRING });
  2079. const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
  2080. User.belongsToMany(Task, { through: 'UserTasks', as: 'Tasks', inverse: 'Users' });
  2081. await this.sequelize.sync({ force: true });
  2082. const [user0, task] = await Promise.all([
  2083. User.create({ id: 12 }),
  2084. Task.create({ id: 50, title: 'get started' }),
  2085. ]);
  2086. await user0.addTask(task.id);
  2087. const user = user0;
  2088. const tasks = await user.getTasks();
  2089. expect(tasks[0].title).to.equal('get started');
  2090. });
  2091. it('should not pass indexes to the join table', async function () {
  2092. const User = this.sequelize.define(
  2093. 'User',
  2094. { username: DataTypes.STRING },
  2095. {
  2096. indexes: [
  2097. {
  2098. name: 'username_unique',
  2099. unique: true,
  2100. method: 'BTREE',
  2101. fields: ['username'],
  2102. },
  2103. ],
  2104. },
  2105. );
  2106. const Task = this.sequelize.define(
  2107. 'Task',
  2108. { title: DataTypes.STRING },
  2109. {
  2110. indexes: [
  2111. {
  2112. name: 'title_index',
  2113. method: 'BTREE',
  2114. fields: ['title'],
  2115. },
  2116. ],
  2117. },
  2118. );
  2119. // create associations
  2120. User.belongsToMany(Task, { through: 'UserTasks' });
  2121. Task.belongsToMany(User, { through: 'UserTasks' });
  2122. await this.sequelize.sync({ force: true });
  2123. });
  2124. it('should catch EmptyResultError when rejectOnEmpty is set', async function () {
  2125. const User = this.sequelize.define(
  2126. 'User',
  2127. { username: DataTypes.STRING },
  2128. { rejectOnEmpty: true },
  2129. );
  2130. const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
  2131. User.belongsToMany(Task, { through: 'UserTasks' });
  2132. Task.belongsToMany(User, { through: 'UserTasks' });
  2133. await this.sequelize.sync({ force: true });
  2134. const [user0, task] = await Promise.all([
  2135. User.create({ id: 12 }),
  2136. Task.create({ id: 50, title: 'get started' }),
  2137. ]);
  2138. await user0.addTask(task);
  2139. const user = user0;
  2140. const tasks = await user.getTasks();
  2141. expect(tasks[0].title).to.equal('get started');
  2142. });
  2143. });
  2144. describe('addMultipleAssociations', () => {
  2145. it('supports both single instance and array', async function () {
  2146. const User = this.sequelize.define('User', { username: DataTypes.STRING });
  2147. const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
  2148. User.belongsToMany(Task, { through: 'UserTasks' });
  2149. Task.belongsToMany(User, { through: 'UserTasks' });
  2150. await this.sequelize.sync({ force: true });
  2151. const [user0, task1, task2] = await Promise.all([
  2152. User.create({ id: 12 }),
  2153. Task.create({ id: 50, title: 'get started' }),
  2154. Task.create({ id: 52, title: 'get done' }),
  2155. ]);
  2156. await Promise.all([user0.addTasks(task1), user0.addTasks([task2])]);
  2157. const user = user0;
  2158. const tasks = await user.getTasks();
  2159. expect(tasks).to.have.length(2);
  2160. expect(
  2161. tasks.some(item => {
  2162. return item.title === 'get started';
  2163. }),
  2164. ).to.be.ok;
  2165. expect(
  2166. tasks.some(item => {
  2167. return item.title === 'get done';
  2168. }),
  2169. ).to.be.ok;
  2170. });
  2171. it('adds associations without removing the current ones', async function () {
  2172. const User = this.sequelize.define('User', { username: DataTypes.STRING });
  2173. const Task = this.sequelize.define('Task', { title: DataTypes.STRING });
  2174. User.belongsToMany(Task, { through: 'UserTasks' });
  2175. Task.belongsToMany(User, { through: 'UserTasks' });
  2176. await this.sequelize.sync({ force: true });
  2177. await User.bulkCreate([{ username: 'foo ' }, { username: 'bar ' }, { username: 'baz ' }]);
  2178. const [task, users1] = await Promise.all([Task.create({ title: 'task' }), User.findAll()]);
  2179. const users = users1;
  2180. await task.setUsers([users1[0]]);
  2181. await task.addUsers([users[1], users[2]]);
  2182. const users0 = await task.getUsers();
  2183. expect(users0).to.have.length(3);
  2184. // Re-add user 0's object, this should be harmless
  2185. // Re-add user 0's id, this should be harmless
  2186. await Promise.all([
  2187. expect(task.addUsers([users[0]])).not.to.be.rejected,
  2188. expect(task.addUsers([users[0].id])).not.to.be.rejected,
  2189. ]);
  2190. expect(await task.getUsers()).to.have.length(3);
  2191. });
  2192. });
  2193. describe('through model validations', () => {
  2194. beforeEach(async function () {
  2195. const Project = this.sequelize.define('Project', {
  2196. name: DataTypes.STRING,
  2197. });
  2198. const Employee = this.sequelize.define('Employee', {
  2199. name: DataTypes.STRING,
  2200. });
  2201. const Participation = this.sequelize.define('Participation', {
  2202. role: {
  2203. type: DataTypes.STRING,
  2204. allowNull: false,
  2205. validate: {
  2206. len: {
  2207. args: [2, 50],
  2208. msg: 'too bad',
  2209. },
  2210. },
  2211. },
  2212. });
  2213. Project.belongsToMany(Employee, {
  2214. as: 'Participants',
  2215. through: Participation,
  2216. inverse: { as: 'Projects' },
  2217. });
  2218. await this.sequelize.sync({ force: true });
  2219. const [project, employee] = await Promise.all([
  2220. Project.create({ name: 'project 1' }),
  2221. Employee.create({ name: 'employee 1' }),
  2222. ]);
  2223. this.project = project;
  2224. this.employee = employee;
  2225. });
  2226. it('runs on add', async function () {
  2227. await expect(this.project.addParticipant(this.employee, { through: { role: '' } })).to.be
  2228. .rejected;
  2229. });
  2230. it('runs on set', async function () {
  2231. await expect(this.project.setParticipants([this.employee], { through: { role: '' } })).to.be
  2232. .rejected;
  2233. });
  2234. it('runs on create', async function () {
  2235. await expect(
  2236. this.project.createParticipant({ name: 'employee 2' }, { through: { role: '' } }),
  2237. ).to.be.rejected;
  2238. });
  2239. });
  2240. describe('optimizations using bulk create, destroy and update', () => {
  2241. beforeEach(function () {
  2242. this.User = this.sequelize.define(
  2243. 'User',
  2244. { username: DataTypes.STRING },
  2245. { timestamps: false },
  2246. );
  2247. this.Task = this.sequelize.define('Task', { title: DataTypes.STRING }, { timestamps: false });
  2248. this.User.belongsToMany(this.Task, { through: 'UserTasks' });
  2249. this.Task.belongsToMany(this.User, { through: 'UserTasks' });
  2250. return this.sequelize.sync({ force: true });
  2251. });
  2252. it('uses one insert into statement', async function () {
  2253. const spy = sinon.spy();
  2254. const [user, task1, task2] = await Promise.all([
  2255. this.User.create({ username: 'foo' }),
  2256. this.Task.create({ id: 12, title: 'task1' }),
  2257. this.Task.create({ id: 15, title: 'task2' }),
  2258. ]);
  2259. await user.setTasks([task1, task2], {
  2260. logging: spy,
  2261. });
  2262. expect(spy.calledTwice).to.be.ok;
  2263. });
  2264. it('uses one delete from statement', async function () {
  2265. const spy = sinon.spy();
  2266. const [user0, task1, task2] = await Promise.all([
  2267. this.User.create({ username: 'foo' }),
  2268. this.Task.create({ title: 'task1' }),
  2269. this.Task.create({ title: 'task2' }),
  2270. ]);
  2271. await user0.setTasks([task1, task2]);
  2272. const user = user0;
  2273. await user.setTasks(null, {
  2274. logging: spy,
  2275. });
  2276. expect(spy.calledTwice).to.be.ok;
  2277. });
  2278. }); // end optimization using bulk create, destroy and update
  2279. describe('join table creation', () => {
  2280. beforeEach(function () {
  2281. this.User = this.sequelize.define(
  2282. 'User',
  2283. { username: DataTypes.STRING },
  2284. { tableName: 'users' },
  2285. );
  2286. this.Task = this.sequelize.define(
  2287. 'Task',
  2288. { title: DataTypes.STRING },
  2289. { tableName: 'tasks' },
  2290. );
  2291. this.User.belongsToMany(this.Task, { through: 'user_has_tasks' });
  2292. this.Task.belongsToMany(this.User, { through: 'user_has_tasks' });
  2293. return this.sequelize.sync({ force: true });
  2294. });
  2295. it('should work with non integer primary keys', async function () {
  2296. const Beacons = this.sequelize.define('Beacon', {
  2297. id: {
  2298. primaryKey: true,
  2299. type: DataTypes.UUID,
  2300. defaultValue: sql.uuidV4,
  2301. },
  2302. name: {
  2303. type: DataTypes.STRING,
  2304. },
  2305. });
  2306. // User not to clash with the beforeEach definition
  2307. const Users = this.sequelize.define('Usar', {
  2308. name: {
  2309. type: DataTypes.STRING,
  2310. },
  2311. });
  2312. Beacons.belongsToMany(Users, { through: 'UserBeacons' });
  2313. Users.belongsToMany(Beacons, { through: 'UserBeacons' });
  2314. await this.sequelize.sync({ force: true });
  2315. });
  2316. it('makes join table non-paranoid by default', () => {
  2317. const paranoidSequelize = Support.createSingleTestSequelizeInstance({
  2318. define: {
  2319. paranoid: true,
  2320. },
  2321. });
  2322. const ParanoidUser = paranoidSequelize.define('ParanoidUser', {});
  2323. const ParanoidTask = paranoidSequelize.define('ParanoidTask', {});
  2324. const taskAssociation = ParanoidUser.belongsToMany(ParanoidTask, { through: 'UserTasks' });
  2325. const userAssociation = ParanoidTask.belongsToMany(ParanoidUser, { through: 'UserTasks' });
  2326. expect(ParanoidUser.options.paranoid).to.be.ok;
  2327. expect(ParanoidTask.options.paranoid).to.be.ok;
  2328. expect(userAssociation.throughModel).to.equal(taskAssociation.throughModel);
  2329. expect(userAssociation.throughModel.options.paranoid).not.to.be.ok;
  2330. });
  2331. it('should allow creation of a paranoid join table', () => {
  2332. const paranoidSequelize = Support.createSingleTestSequelizeInstance({
  2333. define: {
  2334. paranoid: true,
  2335. },
  2336. });
  2337. const ParanoidUser = paranoidSequelize.define('ParanoidUser', {});
  2338. const ParanoidTask = paranoidSequelize.define('ParanoidTask', {});
  2339. const taskAssociation = ParanoidUser.belongsToMany(ParanoidTask, {
  2340. through: {
  2341. model: 'UserTasks',
  2342. paranoid: true,
  2343. },
  2344. });
  2345. const userAssociation = ParanoidTask.belongsToMany(ParanoidUser, {
  2346. through: {
  2347. model: 'UserTasks',
  2348. paranoid: true,
  2349. },
  2350. });
  2351. expect(ParanoidUser.options.paranoid).to.be.ok;
  2352. expect(ParanoidTask.options.paranoid).to.be.ok;
  2353. expect(userAssociation.throughModel).to.equal(taskAssociation.throughModel);
  2354. expect(userAssociation.throughModel.options.paranoid).to.be.ok;
  2355. });
  2356. });
  2357. describe('foreign keys', () => {
  2358. it('generates camelCase foreign keys if underscored is not set on the through model', function () {
  2359. const User = this.sequelize.define(
  2360. 'User',
  2361. {},
  2362. {
  2363. tableName: 'users',
  2364. underscored: true,
  2365. timestamps: false,
  2366. },
  2367. );
  2368. const Place = this.sequelize.define(
  2369. 'Place',
  2370. {},
  2371. {
  2372. tableName: 'places',
  2373. underscored: true,
  2374. timestamps: false,
  2375. },
  2376. );
  2377. User.belongsToMany(Place, { through: 'user_places' });
  2378. Place.belongsToMany(User, { through: 'user_places' });
  2379. const attributes = this.sequelize.models.getOrThrow('user_places').getAttributes();
  2380. expect(attributes.placeId.field).to.equal('placeId');
  2381. expect(attributes.userId.field).to.equal('userId');
  2382. });
  2383. it('generates snake_case foreign keys if underscored is set on the through model', function () {
  2384. const User = this.sequelize.define('User', {}, { timestamps: false });
  2385. const Place = this.sequelize.define('Place', {}, { timestamps: false });
  2386. const UserPlaces = this.sequelize.define(
  2387. 'UserPlaces',
  2388. {},
  2389. { underscored: true, timestamps: false },
  2390. );
  2391. User.belongsToMany(Place, { through: UserPlaces });
  2392. Place.belongsToMany(User, { through: UserPlaces });
  2393. const attributes = UserPlaces.getAttributes();
  2394. expect(attributes.placeId.field).to.equal('place_id');
  2395. expect(attributes.userId.field).to.equal('user_id');
  2396. });
  2397. it('should infer otherKey from paired BTM relationship with a through string defined', function () {
  2398. const User = this.sequelize.define('User', {});
  2399. const Place = this.sequelize.define('Place', {});
  2400. const Places = User.belongsToMany(Place, {
  2401. through: 'user_places',
  2402. foreignKey: 'user_id',
  2403. otherKey: 'place_id',
  2404. });
  2405. expect(Places.foreignKey).to.equal('user_id');
  2406. expect(Places.pairedWith.foreignKey).to.equal('place_id');
  2407. expect(Places.otherKey).to.equal('place_id');
  2408. expect(Places.pairedWith.otherKey).to.equal('user_id');
  2409. });
  2410. });
  2411. describe('foreign key with fields specified', () => {
  2412. beforeEach(function () {
  2413. this.User = this.sequelize.define('User', { name: DataTypes.STRING });
  2414. this.Project = this.sequelize.define('Project', { name: DataTypes.STRING });
  2415. this.Puppy = this.sequelize.define('Puppy', { breed: DataTypes.STRING });
  2416. this.User.belongsToMany(this.Project, {
  2417. through: 'user_projects',
  2418. as: 'Projects',
  2419. inverse: {
  2420. as: 'Users',
  2421. },
  2422. foreignKey: {
  2423. field: 'user_id',
  2424. name: 'userId',
  2425. },
  2426. otherKey: {
  2427. field: 'project_id',
  2428. name: 'projectId',
  2429. },
  2430. });
  2431. });
  2432. it('should correctly get associations even after a child instance is deleted', async function () {
  2433. const spy = sinon.spy();
  2434. await this.sequelize.sync({ force: true });
  2435. const [user3, project1, project2] = await Promise.all([
  2436. this.User.create({ name: 'Matt' }),
  2437. this.Project.create({ name: 'Good Will Hunting' }),
  2438. this.Project.create({ name: 'The Departed' }),
  2439. ]);
  2440. await user3.addProjects([project1, project2], {
  2441. logging: spy,
  2442. });
  2443. const user2 = user3;
  2444. expect(spy).to.have.been.calledTwice;
  2445. spy.resetHistory();
  2446. const [user1, projects0] = await Promise.all([
  2447. user2,
  2448. user2.getProjects({
  2449. logging: spy,
  2450. }),
  2451. ]);
  2452. expect(spy.calledOnce).to.be.ok;
  2453. const project0 = projects0[0];
  2454. expect(project0).to.be.ok;
  2455. await project0.destroy();
  2456. const user0 = user1;
  2457. const user = await this.User.findOne({
  2458. where: { id: user0.id },
  2459. include: [{ model: this.Project, as: 'Projects' }],
  2460. });
  2461. const projects = user.Projects;
  2462. const project = projects[0];
  2463. expect(project).to.be.ok;
  2464. });
  2465. it('should correctly get associations when doubly linked', async function () {
  2466. const spy = sinon.spy();
  2467. await this.sequelize.sync({ force: true });
  2468. const [user0, project0] = await Promise.all([
  2469. this.User.create({ name: 'Matt' }),
  2470. this.Project.create({ name: 'Good Will Hunting' }),
  2471. ]);
  2472. this.user = user0;
  2473. this.project = project0;
  2474. await user0.addProject(project0, { logging: spy });
  2475. const user = user0;
  2476. expect(spy.calledTwice).to.be.ok; // Once for SELECT, once for INSERT
  2477. spy.resetHistory();
  2478. const projects = await user.getProjects({
  2479. logging: spy,
  2480. });
  2481. const project = projects[0];
  2482. expect(spy.calledOnce).to.be.ok;
  2483. spy.resetHistory();
  2484. expect(project).to.be.ok;
  2485. await this.user.removeProject(project, {
  2486. logging: spy,
  2487. });
  2488. await project;
  2489. expect(spy).to.have.been.calledOnce;
  2490. });
  2491. it('should be able to handle nested includes properly', async function () {
  2492. this.Group = this.sequelize.define('Group', { groupName: DataTypes.STRING });
  2493. this.Group.belongsToMany(this.User, {
  2494. through: 'group_users',
  2495. as: 'Users',
  2496. foreignKey: {
  2497. field: 'group_id',
  2498. name: 'groupId',
  2499. },
  2500. otherKey: {
  2501. field: 'user_id',
  2502. name: 'userId',
  2503. },
  2504. });
  2505. this.User.belongsToMany(this.Group, {
  2506. through: 'group_users',
  2507. as: 'Groups',
  2508. foreignKey: {
  2509. field: 'user_id',
  2510. name: 'userId',
  2511. },
  2512. otherKey: {
  2513. field: 'group_id',
  2514. name: 'groupId',
  2515. },
  2516. });
  2517. await this.sequelize.sync({ force: true });
  2518. const [group1, user0, project0] = await Promise.all([
  2519. this.Group.create({ groupName: 'The Illuminati' }),
  2520. this.User.create({ name: 'Matt' }),
  2521. this.Project.create({ name: 'Good Will Hunting' }),
  2522. ]);
  2523. await user0.addProject(project0);
  2524. await group1.addUser(user0);
  2525. const group0 = group1;
  2526. // get the group and include both the users in the group and their project's
  2527. const groups = await this.Group.findAll({
  2528. where: { id: group0.id },
  2529. include: [
  2530. {
  2531. model: this.User,
  2532. as: 'Users',
  2533. include: [{ model: this.Project, as: 'Projects' }],
  2534. },
  2535. ],
  2536. });
  2537. const group = groups[0];
  2538. expect(group).to.be.ok;
  2539. const user = group.Users[0];
  2540. expect(user).to.be.ok;
  2541. const project = user.Projects[0];
  2542. expect(project).to.be.ok;
  2543. expect(project.name).to.equal('Good Will Hunting');
  2544. });
  2545. });
  2546. describe('primary key handling for join table', () => {
  2547. beforeEach(function () {
  2548. this.User = this.sequelize.define(
  2549. 'User',
  2550. { username: DataTypes.STRING },
  2551. { tableName: 'users' },
  2552. );
  2553. this.Task = this.sequelize.define(
  2554. 'Task',
  2555. { title: DataTypes.STRING },
  2556. { tableName: 'tasks' },
  2557. );
  2558. });
  2559. it('removes the primary key if it was added by sequelize', function () {
  2560. this.UserTasks = this.sequelize.define('usertasks', {});
  2561. this.User.belongsToMany(this.Task, { through: this.UserTasks });
  2562. this.Task.belongsToMany(this.User, { through: this.UserTasks });
  2563. expect(Object.keys(this.UserTasks.primaryKeys).sort()).to.deep.equal(['taskId', 'userId']);
  2564. });
  2565. it('keeps the primary key if it was added by the user', function () {
  2566. this.UserTasks = this.sequelize.define('UserTask', {
  2567. id: {
  2568. type: DataTypes.INTEGER,
  2569. autoincrement: true,
  2570. primaryKey: true,
  2571. },
  2572. });
  2573. this.UserTasks2 = this.sequelize.define('UserTask2', {
  2574. userTasksId: {
  2575. type: DataTypes.INTEGER,
  2576. autoincrement: true,
  2577. primaryKey: true,
  2578. },
  2579. });
  2580. this.User.belongsToMany(this.Task, { through: this.UserTasks });
  2581. this.User.belongsToMany(this.Task, {
  2582. through: this.UserTasks2,
  2583. as: 'otherTasksB',
  2584. inverse: { as: 'otherUsers' },
  2585. });
  2586. expect(Object.keys(this.UserTasks.primaryKeys)).to.deep.equal(['id']);
  2587. expect(Object.keys(this.UserTasks2.primaryKeys)).to.deep.equal(['userTasksId']);
  2588. for (const model of [this.UserTasks, this.UserTasks2]) {
  2589. const index = model.getIndexes()[0];
  2590. expect(index.fields.sort()).to.deep.equal(['taskId', 'userId']);
  2591. }
  2592. });
  2593. describe('without sync', () => {
  2594. beforeEach(async function () {
  2595. await this.sequelize.queryInterface.createTable('users', {
  2596. id: {
  2597. type: DataTypes.INTEGER,
  2598. primaryKey: true,
  2599. autoIncrement: true,
  2600. },
  2601. username: DataTypes.STRING,
  2602. createdAt: DataTypes.DATE,
  2603. updatedAt: DataTypes.DATE,
  2604. });
  2605. await this.sequelize.queryInterface.createTable('tasks', {
  2606. id: {
  2607. type: DataTypes.INTEGER,
  2608. primaryKey: true,
  2609. autoIncrement: true,
  2610. },
  2611. title: DataTypes.STRING,
  2612. createdAt: DataTypes.DATE,
  2613. updatedAt: DataTypes.DATE,
  2614. });
  2615. return this.sequelize.queryInterface.createTable('users_tasks', {
  2616. taskId: DataTypes.INTEGER,
  2617. userId: DataTypes.INTEGER,
  2618. createdAt: DataTypes.DATE,
  2619. updatedAt: DataTypes.DATE,
  2620. });
  2621. });
  2622. it('removes all associations', async function () {
  2623. this.UsersTasks = this.sequelize.define('UsersTasks', {}, { tableName: 'users_tasks' });
  2624. this.User.belongsToMany(this.Task, { through: this.UsersTasks });
  2625. this.Task.belongsToMany(this.User, { through: this.UsersTasks });
  2626. expect(Object.keys(this.UsersTasks.primaryKeys).sort()).to.deep.equal(['taskId', 'userId']);
  2627. const [user, task] = await Promise.all([
  2628. this.User.create({ username: 'foo' }),
  2629. this.Task.create({ title: 'foo' }),
  2630. ]);
  2631. await user.addTask(task);
  2632. await user.setTasks(null);
  2633. expect(await user.getTasks()).to.have.length(0);
  2634. });
  2635. });
  2636. });
  2637. describe('through', () => {
  2638. describe('paranoid', () => {
  2639. beforeEach(async function () {
  2640. this.User = this.sequelize.define('User', {});
  2641. this.Project = this.sequelize.define('Project', {});
  2642. this.UserProjects = this.sequelize.define(
  2643. 'UserProjects',
  2644. {},
  2645. {
  2646. paranoid: true,
  2647. },
  2648. );
  2649. this.User.belongsToMany(this.Project, { through: this.UserProjects });
  2650. this.Project.belongsToMany(this.User, { through: this.UserProjects });
  2651. await this.sequelize.sync();
  2652. this.users = await Promise.all([
  2653. this.User.create(),
  2654. this.User.create(),
  2655. this.User.create(),
  2656. ]);
  2657. this.projects = await Promise.all([
  2658. this.Project.create(),
  2659. this.Project.create(),
  2660. this.Project.create(),
  2661. ]);
  2662. });
  2663. it('gets only non-deleted records by default', async function () {
  2664. await this.users[0].addProjects(this.projects);
  2665. await this.UserProjects.destroy({
  2666. where: {
  2667. projectId: this.projects[0].id,
  2668. },
  2669. });
  2670. const result = await this.users[0].getProjects();
  2671. expect(result.length).to.equal(2);
  2672. });
  2673. it('returns both deleted and non-deleted records with paranoid=false', async function () {
  2674. await this.users[0].addProjects(this.projects);
  2675. await this.UserProjects.destroy({
  2676. where: {
  2677. projectId: this.projects[0].id,
  2678. },
  2679. });
  2680. const result = await this.users[0].getProjects({ through: { paranoid: false } });
  2681. expect(result.length).to.equal(3);
  2682. });
  2683. it('hasAssociation also respects paranoid option', async function () {
  2684. await this.users[0].addProjects(this.projects);
  2685. await this.UserProjects.destroy({
  2686. where: {
  2687. projectId: this.projects[0].id,
  2688. },
  2689. });
  2690. expect(
  2691. await this.users[0].hasProjects(this.projects[0], { through: { paranoid: false } }),
  2692. ).to.equal(true);
  2693. expect(await this.users[0].hasProjects(this.projects[0])).to.equal(false);
  2694. expect(await this.users[0].hasProjects(this.projects[1])).to.equal(true);
  2695. expect(await this.users[0].hasProjects(this.projects)).to.equal(false);
  2696. });
  2697. });
  2698. describe('fetching from join table', () => {
  2699. beforeEach(function () {
  2700. this.User = this.sequelize.define('User', {});
  2701. this.Project = this.sequelize.define('Project', {});
  2702. this.UserProjects = this.sequelize.define('UserProjects', {
  2703. status: DataTypes.STRING,
  2704. data: DataTypes.INTEGER,
  2705. });
  2706. this.User.belongsToMany(this.Project, { through: this.UserProjects });
  2707. this.Project.belongsToMany(this.User, { through: this.UserProjects });
  2708. return this.sequelize.sync();
  2709. });
  2710. it('should contain the data from the join table on .UserProjects a DAO', async function () {
  2711. const [user, project0] = await Promise.all([this.User.create(), this.Project.create()]);
  2712. await user.addProject(project0, { through: { status: 'active', data: 42 } });
  2713. const projects = await user.getProjects();
  2714. const project = projects[0];
  2715. expect(project.userProject).to.be.ok;
  2716. expect(project.status).not.to.exist;
  2717. expect(project.userProject.status).to.equal('active');
  2718. expect(project.userProject.data).to.equal(42);
  2719. });
  2720. it('should be able to alias the default name of the join table', async function () {
  2721. const [user, project0] = await Promise.all([this.User.create(), this.Project.create()]);
  2722. await user.addProject(project0, { through: { status: 'active', data: 42 } });
  2723. const users = await this.User.findAll({
  2724. include: [
  2725. {
  2726. model: this.Project,
  2727. through: {
  2728. as: 'myProject',
  2729. },
  2730. },
  2731. ],
  2732. });
  2733. const project = users[0].projects[0];
  2734. expect(project.UserProjects).not.to.exist;
  2735. expect(project.status).not.to.exist;
  2736. expect(project.myProject).to.be.ok;
  2737. expect(project.myProject.status).to.equal('active');
  2738. expect(project.myProject.data).to.equal(42);
  2739. });
  2740. it('should be able to limit the join table attributes returned', async function () {
  2741. const [user, project0] = await Promise.all([this.User.create(), this.Project.create()]);
  2742. await user.addProject(project0, { through: { status: 'active', data: 42 } });
  2743. const projects = await user.getProjects({ joinTableAttributes: ['status'] });
  2744. const project = projects[0];
  2745. expect(project.userProject).to.be.ok;
  2746. expect(project.status).not.to.exist;
  2747. expect(project.userProject.status).to.equal('active');
  2748. expect(project.userProject.data).not.to.exist;
  2749. });
  2750. });
  2751. describe('inserting in join table', () => {
  2752. beforeEach(function () {
  2753. this.User = this.sequelize.define('User', {});
  2754. this.Project = this.sequelize.define('Project', {});
  2755. this.UserProjects = this.sequelize.define('UserProjects', {
  2756. status: DataTypes.STRING,
  2757. data: DataTypes.INTEGER,
  2758. });
  2759. this.User.belongsToMany(this.Project, { through: this.UserProjects });
  2760. this.Project.belongsToMany(this.User, { through: this.UserProjects });
  2761. return this.sequelize.sync();
  2762. });
  2763. describe('add', () => {
  2764. it('should insert data provided on the object into the join table', async function () {
  2765. const [u, p] = await Promise.all([this.User.create(), this.Project.create()]);
  2766. p.UserProjects = { status: 'active' };
  2767. await u.addProject(p);
  2768. const up = await this.UserProjects.findOne({ where: { userId: u.id, projectId: p.id } });
  2769. expect(up.status).to.equal('active');
  2770. });
  2771. it('should insert data provided as a second argument into the join table', async function () {
  2772. const [u, p] = await Promise.all([this.User.create(), this.Project.create()]);
  2773. await u.addProject(p, { through: { status: 'active' } });
  2774. const up = await this.UserProjects.findOne({ where: { userId: u.id, projectId: p.id } });
  2775. expect(up.status).to.equal('active');
  2776. });
  2777. it('should be able to add twice (second call result in UPDATE call) without any attributes (and timestamps off) on the through model', async function () {
  2778. const Worker = this.sequelize.define('Worker', {}, { timestamps: false });
  2779. const Task = this.sequelize.define('Task', {}, { timestamps: false });
  2780. const WorkerTasks = this.sequelize.define('WorkerTasks', {}, { timestamps: false });
  2781. Worker.belongsToMany(Task, { through: WorkerTasks });
  2782. Task.belongsToMany(Worker, { through: WorkerTasks });
  2783. await this.sequelize.sync({ force: true });
  2784. const worker = await Worker.create({ id: 1337 });
  2785. const task = await Task.create({ id: 7331 });
  2786. await worker.addTask(task);
  2787. await worker.addTask(task);
  2788. });
  2789. it('should be able to add twice (second call result in UPDATE call) with custom primary keys and without any attributes (and timestamps off) on the through model', async function () {
  2790. const Worker = this.sequelize.define(
  2791. 'Worker',
  2792. {
  2793. id: {
  2794. type: DataTypes.INTEGER,
  2795. allowNull: false,
  2796. primaryKey: true,
  2797. autoIncrement: true,
  2798. },
  2799. },
  2800. { timestamps: false },
  2801. );
  2802. const Task = this.sequelize.define(
  2803. 'Task',
  2804. {
  2805. id: {
  2806. type: DataTypes.INTEGER,
  2807. allowNull: false,
  2808. primaryKey: true,
  2809. autoIncrement: true,
  2810. },
  2811. },
  2812. { timestamps: false },
  2813. );
  2814. const WorkerTasks = this.sequelize.define(
  2815. 'WorkerTasks',
  2816. {
  2817. id: {
  2818. type: DataTypes.INTEGER,
  2819. allowNull: false,
  2820. primaryKey: true,
  2821. autoIncrement: true,
  2822. },
  2823. },
  2824. { timestamps: false },
  2825. );
  2826. Worker.belongsToMany(Task, { through: WorkerTasks });
  2827. Task.belongsToMany(Worker, { through: WorkerTasks });
  2828. await this.sequelize.sync({ force: true });
  2829. const worker = await Worker.create({ id: 1337 });
  2830. const task = await Task.create({ id: 7331 });
  2831. await worker.addTask(task);
  2832. await worker.addTask(task);
  2833. });
  2834. it('should be able to create an instance along with its many-to-many association which has an extra column in the junction table', async function () {
  2835. const Foo = this.sequelize.define('foo', { name: DataTypes.STRING });
  2836. const Bar = this.sequelize.define('bar', { name: DataTypes.STRING });
  2837. const FooBar = this.sequelize.define('foobar', { baz: DataTypes.STRING });
  2838. Foo.belongsToMany(Bar, { through: FooBar });
  2839. Bar.belongsToMany(Foo, { through: FooBar });
  2840. await this.sequelize.sync({ force: true });
  2841. const foo0 = await Foo.create(
  2842. {
  2843. name: 'foo...',
  2844. bars: [
  2845. {
  2846. name: 'bar...',
  2847. foobar: {
  2848. baz: 'baz...',
  2849. },
  2850. },
  2851. ],
  2852. },
  2853. {
  2854. include: Bar,
  2855. },
  2856. );
  2857. expect(foo0.name).to.equal('foo...');
  2858. expect(foo0.bars).to.have.length(1);
  2859. expect(foo0.bars[0].name).to.equal('bar...');
  2860. expect(foo0.bars[0].foobar).to.not.equal(null);
  2861. expect(foo0.bars[0].foobar.baz).to.equal('baz...');
  2862. const foo = await Foo.findOne({ include: Bar });
  2863. expect(foo.name).to.equal('foo...');
  2864. expect(foo.bars).to.have.length(1);
  2865. expect(foo.bars[0].name).to.equal('bar...');
  2866. expect(foo.bars[0].foobar).to.not.equal(null);
  2867. expect(foo.bars[0].foobar.baz).to.equal('baz...');
  2868. });
  2869. });
  2870. describe('set', () => {
  2871. it('should be able to combine properties on the associated objects, and default values', async function () {
  2872. await this.Project.bulkCreate([{}, {}]);
  2873. const [user, projects] = await Promise.all([
  2874. this.User.create(),
  2875. await this.Project.findAll(),
  2876. ]);
  2877. const p1 = projects[0];
  2878. const p2 = projects[1];
  2879. p1.UserProjects = { status: 'inactive' };
  2880. await user.setProjects([p1, p2], { through: { status: 'active' } });
  2881. const [up1, up2] = await Promise.all([
  2882. this.UserProjects.findOne({ where: { userId: user.id, projectId: p1.id } }),
  2883. this.UserProjects.findOne({ where: { userId: user.id, projectId: p2.id } }),
  2884. ]);
  2885. expect(up1.status).to.equal('inactive');
  2886. expect(up2.status).to.equal('active');
  2887. });
  2888. it('should be able to set twice (second call result in UPDATE calls) without any attributes (and timestamps off) on the through model', async function () {
  2889. const Worker = this.sequelize.define('Worker', {}, { timestamps: false });
  2890. const Task = this.sequelize.define('Task', {}, { timestamps: false });
  2891. const WorkerTasks = this.sequelize.define('WorkerTasks', {}, { timestamps: false });
  2892. Worker.belongsToMany(Task, { through: WorkerTasks });
  2893. Task.belongsToMany(Worker, { through: WorkerTasks });
  2894. await this.sequelize.sync({ force: true });
  2895. const [worker0, tasks0] = await Promise.all([
  2896. dialect === 'db2' ? Worker.create({ id: 1 }) : Worker.create(),
  2897. Task.bulkCreate([{}, {}]).then(() => {
  2898. return Task.findAll();
  2899. }),
  2900. ]);
  2901. await worker0.setTasks(tasks0);
  2902. const [worker, tasks] = [worker0, tasks0];
  2903. await worker.setTasks(tasks);
  2904. });
  2905. });
  2906. describe('query with through.where', () => {
  2907. it('should support query the through model', async function () {
  2908. const user = await this.User.create();
  2909. await Promise.all([
  2910. user.createProject({}, { through: { status: 'active', data: 1 } }),
  2911. user.createProject({}, { through: { status: 'inactive', data: 2 } }),
  2912. user.createProject({}, { through: { status: 'inactive', data: 3 } }),
  2913. ]);
  2914. const [activeProjects, inactiveProjectCount] = await Promise.all([
  2915. user.getProjects({ through: { where: { status: 'active' } } }),
  2916. user.countProjects({ through: { where: { status: 'inactive' } } }),
  2917. ]);
  2918. expect(activeProjects).to.have.lengthOf(1);
  2919. expect(inactiveProjectCount).to.eql(2);
  2920. });
  2921. });
  2922. });
  2923. describe('removing from the join table', () => {
  2924. it('should remove a single entry without any attributes (and timestamps off) on the through model', async function () {
  2925. const Worker = this.sequelize.define('Worker', {}, { timestamps: false });
  2926. const Task = this.sequelize.define('Task', {}, { timestamps: false });
  2927. const WorkerTasks = this.sequelize.define('WorkerTasks', {}, { timestamps: false });
  2928. Worker.belongsToMany(Task, { through: WorkerTasks });
  2929. Task.belongsToMany(Worker, { through: WorkerTasks });
  2930. // Test setup
  2931. await this.sequelize.sync({ force: true });
  2932. const [worker, tasks0] = await Promise.all([
  2933. dialect === 'db2' ? Worker.create({ id: 1 }) : Worker.create({}),
  2934. Task.bulkCreate([{}, {}, {}]).then(() => {
  2935. return Task.findAll();
  2936. }),
  2937. ]);
  2938. // Set all tasks, then remove one task by instance, then remove one task by id, then return all tasks
  2939. await worker.setTasks(tasks0);
  2940. await worker.removeTask(tasks0[0]);
  2941. await worker.removeTask(tasks0[1].id);
  2942. const tasks = await worker.getTasks();
  2943. expect(tasks.length).to.equal(1);
  2944. });
  2945. it('should remove multiple entries without any attributes (and timestamps off) on the through model', async function () {
  2946. const Worker = this.sequelize.define('Worker', {}, { timestamps: false });
  2947. const Task = this.sequelize.define('Task', {}, { timestamps: false });
  2948. const WorkerTasks = this.sequelize.define('WorkerTasks', {}, { timestamps: false });
  2949. Worker.belongsToMany(Task, { through: WorkerTasks });
  2950. Task.belongsToMany(Worker, { through: WorkerTasks });
  2951. // Test setup
  2952. await this.sequelize.sync({ force: true });
  2953. const [worker, tasks0] = await Promise.all([
  2954. dialect === 'db2' ? Worker.create({ id: 1 }) : Worker.create({}),
  2955. Task.bulkCreate([{}, {}, {}, {}, {}]).then(() => {
  2956. return Task.findAll();
  2957. }),
  2958. ]);
  2959. // Set all tasks, then remove two tasks by instance, then remove two tasks by id, then return all tasks
  2960. await worker.setTasks(tasks0);
  2961. await worker.removeTasks([tasks0[0], tasks0[1]]);
  2962. await worker.removeTasks([tasks0[2].id, tasks0[3].id]);
  2963. const tasks = await worker.getTasks();
  2964. expect(tasks.length).to.equal(1);
  2965. });
  2966. });
  2967. });
  2968. describe('multiple hasMany', () => {
  2969. beforeEach(function () {
  2970. this.User = this.sequelize.define('user', { name: DataTypes.STRING });
  2971. this.Project = this.sequelize.define('project', { projectName: DataTypes.STRING });
  2972. });
  2973. describe('project has owners and users and owners and users have projects', () => {
  2974. beforeEach(function () {
  2975. this.Project.belongsToMany(this.User, {
  2976. as: 'owners',
  2977. through: 'projectOwners',
  2978. inverse: { as: 'ownedProjects' },
  2979. });
  2980. this.Project.belongsToMany(this.User, {
  2981. as: 'users',
  2982. through: 'projectUsers',
  2983. inverse: { as: 'memberProjects' },
  2984. });
  2985. return this.sequelize.sync({ force: true });
  2986. });
  2987. it('correctly sets user and owner', async function () {
  2988. const p1 = this.Project.build({ projectName: 'p1' });
  2989. const u1 = this.User.build({ name: 'u1' });
  2990. const u2 = this.User.build({ name: 'u2' });
  2991. await p1.save();
  2992. await u1.save();
  2993. await u2.save();
  2994. await p1.setUsers([u1]);
  2995. await p1.setOwners([u2]);
  2996. });
  2997. });
  2998. });
  2999. describe('Foreign key constraints', () => {
  3000. beforeEach(function () {
  3001. this.Task = this.sequelize.define('task', { title: DataTypes.STRING });
  3002. this.User = this.sequelize.define('user', { username: DataTypes.STRING });
  3003. this.UserTasks = this.sequelize.define('tasksusers', {
  3004. userId: DataTypes.INTEGER,
  3005. taskId: DataTypes.INTEGER,
  3006. });
  3007. });
  3008. it('can cascade deletes both ways by default', async function () {
  3009. this.User.belongsToMany(this.Task, { through: 'tasksusers' });
  3010. this.Task.belongsToMany(this.User, { through: 'tasksusers' });
  3011. await this.sequelize.sync({ force: true });
  3012. const [user1, task1, user2, task2] = await Promise.all([
  3013. this.User.create({ id: 67, username: 'foo' }),
  3014. this.Task.create({ id: 52, title: 'task' }),
  3015. this.User.create({ id: 89, username: 'bar' }),
  3016. this.Task.create({ id: 42, title: 'kast' }),
  3017. ]);
  3018. await Promise.all([user1.setTasks([task1]), task2.setUsers([user2])]);
  3019. await Promise.all([user1.destroy(), task2.destroy()]);
  3020. const [tu1, tu2] = await Promise.all([
  3021. this.sequelize.models.getOrThrow('tasksusers').findAll({ where: { userId: user1.id } }),
  3022. this.sequelize.models.getOrThrow('tasksusers').findAll({ where: { taskId: task2.id } }),
  3023. this.User.findOne({
  3024. where: { username: 'Franz Joseph' },
  3025. include: [
  3026. {
  3027. model: this.Task,
  3028. where: {
  3029. title: {
  3030. [Op.ne]: 'task',
  3031. },
  3032. },
  3033. },
  3034. ],
  3035. }),
  3036. ]);
  3037. expect(tu1).to.have.length(0);
  3038. expect(tu2).to.have.length(0);
  3039. });
  3040. if (current.dialect.supports.constraints.restrict) {
  3041. it('can restrict deletes both ways', async function () {
  3042. this.User.belongsToMany(this.Task, {
  3043. through: 'tasksusers',
  3044. foreignKey: { onDelete: 'RESTRICT' },
  3045. otherKey: { onDelete: 'RESTRICT' },
  3046. });
  3047. await this.sequelize.sync({ force: true });
  3048. const [user1, task1, user2, task2] = await Promise.all([
  3049. this.User.create({ id: 67, username: 'foo' }),
  3050. this.Task.create({ id: 52, title: 'task' }),
  3051. this.User.create({ id: 89, username: 'bar' }),
  3052. this.Task.create({ id: 42, title: 'kast' }),
  3053. ]);
  3054. await Promise.all([user1.setTasks([task1]), task2.setUsers([user2])]);
  3055. await Promise.all([
  3056. expect(user1.destroy()).to.have.been.rejectedWith(Sequelize.ForeignKeyConstraintError), // Fails because of
  3057. // RESTRICT constraint
  3058. expect(task2.destroy()).to.have.been.rejectedWith(Sequelize.ForeignKeyConstraintError),
  3059. ]);
  3060. });
  3061. it('can cascade and restrict deletes', async function () {
  3062. this.User.belongsToMany(this.Task, {
  3063. through: 'tasksusers',
  3064. foreignKey: { onDelete: 'RESTRICT' },
  3065. otherKey: { onDelete: 'CASCADE' },
  3066. });
  3067. await this.sequelize.sync({ force: true });
  3068. const [user1, task1, user2, task2] = await Promise.all([
  3069. this.User.create({ id: 67, username: 'foo' }),
  3070. this.Task.create({ id: 52, title: 'task' }),
  3071. this.User.create({ id: 89, username: 'bar' }),
  3072. this.Task.create({ id: 42, title: 'kast' }),
  3073. ]);
  3074. await Promise.all([user1.setTasks([task1]), task2.setUsers([user2])]);
  3075. await Promise.all([
  3076. expect(user1.destroy()).to.have.been.rejectedWith(Sequelize.ForeignKeyConstraintError), // Fails because of
  3077. // RESTRICT constraint
  3078. task2.destroy(),
  3079. ]);
  3080. const usertasks = await this.sequelize.models
  3081. .getOrThrow('tasksusers')
  3082. .findAll({ where: { taskId: task2.id } });
  3083. // This should not exist because deletes cascade
  3084. expect(usertasks).to.have.length(0);
  3085. });
  3086. }
  3087. it('should be possible to remove all constraints', async function () {
  3088. this.User.belongsToMany(this.Task, {
  3089. foreignKeyConstraints: false,
  3090. through: 'tasksusers',
  3091. inverse: { foreignKeyConstraints: false },
  3092. });
  3093. const Through = this.sequelize.models.getOrThrow('tasksusers');
  3094. expect(Through.getAttributes().taskId.references).to.eq(
  3095. undefined,
  3096. 'Attribute taskId should not be a foreign key',
  3097. );
  3098. expect(Through.getAttributes().userId.references).to.eq(
  3099. undefined,
  3100. 'Attribute userId should not be a foreign key',
  3101. );
  3102. await this.sequelize.sync({ force: true });
  3103. const [user1, task1, user2, task2] = await Promise.all([
  3104. this.User.create({ id: 67, username: 'foo' }),
  3105. this.Task.create({ id: 52, title: 'task' }),
  3106. this.User.create({ id: 89, username: 'bar' }),
  3107. this.Task.create({ id: 42, title: 'kast' }),
  3108. ]);
  3109. await Promise.all([user1.setTasks([task1]), task2.setUsers([user2])]);
  3110. await Promise.all([user1.destroy(), task2.destroy()]);
  3111. const [ut1, ut2] = await Promise.all([
  3112. this.sequelize.models.getOrThrow('tasksusers').findAll({ where: { userId: user1.id } }),
  3113. this.sequelize.models.getOrThrow('tasksusers').findAll({ where: { taskId: task2.id } }),
  3114. ]);
  3115. expect(ut1).to.have.length(1);
  3116. expect(ut2).to.have.length(1);
  3117. });
  3118. });
  3119. describe('Association options', () => {
  3120. describe('allows the user to provide an attribute definition object as foreignKey', () => {
  3121. it('works when taking a column directly from the object', function () {
  3122. const Project = this.sequelize.define('project', {});
  3123. const User = this.sequelize.define('user', {
  3124. uid: {
  3125. type: DataTypes.INTEGER,
  3126. primaryKey: true,
  3127. },
  3128. });
  3129. const UserProjects = User.belongsToMany(Project, {
  3130. foreignKey: { name: 'user_id', defaultValue: 42 },
  3131. through: 'UserProjects',
  3132. });
  3133. expect(UserProjects.through.model.getAttributes().user_id).to.be.ok;
  3134. const targetTable = UserProjects.through.model.getAttributes().user_id.references.table;
  3135. assert(typeof targetTable === 'object');
  3136. expect(targetTable).to.deep.equal(User.table);
  3137. expect(UserProjects.through.model.getAttributes().user_id.references.key).to.equal('uid');
  3138. expect(UserProjects.through.model.getAttributes().user_id.defaultValue).to.equal(42);
  3139. });
  3140. });
  3141. it('should throw an error if foreignKey and as result in a name clash', function () {
  3142. const User = this.sequelize.define('user', {
  3143. user: DataTypes.INTEGER,
  3144. });
  3145. expect(User.belongsToMany.bind(User, User, { as: 'user', through: 'UserUser' })).to.throw(
  3146. "Naming collision between attribute 'user' and association 'user' on model user. To remedy this, change the \"as\" options in your association definition",
  3147. );
  3148. });
  3149. });
  3150. describe('thisAssociations', () => {
  3151. it('should work with this reference', async function () {
  3152. const User = this.sequelize.define('User', {
  3153. name: DataTypes.STRING(100),
  3154. });
  3155. const Follow = this.sequelize.define('Follow');
  3156. User.belongsToMany(User, { through: Follow, as: 'Users', inverse: { as: 'Fans' } });
  3157. await this.sequelize.sync({ force: true });
  3158. const users = await Promise.all([
  3159. User.create({ name: 'Khsama' }),
  3160. User.create({ name: 'Vivek' }),
  3161. User.create({ name: 'Satya' }),
  3162. ]);
  3163. await Promise.all([
  3164. users[0].addFan(users[1]),
  3165. users[1].addUser(users[2]),
  3166. users[2].addFan(users[0]),
  3167. ]);
  3168. });
  3169. it('should work with custom this reference', async function () {
  3170. const User = this.sequelize.define('User', {
  3171. name: DataTypes.STRING(100),
  3172. });
  3173. const UserFollowers = this.sequelize.define('UserFollower');
  3174. User.belongsToMany(User, {
  3175. as: {
  3176. singular: 'Follower',
  3177. plural: 'Followers',
  3178. },
  3179. through: UserFollowers,
  3180. inverse: {
  3181. as: 'Followings',
  3182. },
  3183. });
  3184. User.belongsToMany(User, {
  3185. as: {
  3186. singular: 'Invitee',
  3187. plural: 'Invitees',
  3188. },
  3189. foreignKey: 'inviteeId',
  3190. through: 'Invites',
  3191. inverse: {
  3192. as: 'Hosts',
  3193. },
  3194. });
  3195. await this.sequelize.sync({ force: true });
  3196. const users = await Promise.all([
  3197. User.create({ name: 'Jalrangi' }),
  3198. User.create({ name: 'Sargrahi' }),
  3199. ]);
  3200. await Promise.all([
  3201. users[0].addFollower(users[1]),
  3202. users[1].addFollower(users[0]),
  3203. users[0].addInvitee(users[1]),
  3204. users[1].addInvitee(users[0]),
  3205. ]);
  3206. });
  3207. });
  3208. describe('Eager loading', () => {
  3209. beforeEach(function () {
  3210. this.Individual = this.sequelize.define('individual', {
  3211. name: DataTypes.STRING,
  3212. });
  3213. this.Hat = this.sequelize.define('hat', {
  3214. name: DataTypes.STRING,
  3215. });
  3216. this.Event = this.sequelize.define('event', {});
  3217. this.Individual.belongsToMany(this.Hat, {
  3218. through: this.Event,
  3219. as: {
  3220. singular: 'personwearinghat',
  3221. plural: 'personwearinghats',
  3222. },
  3223. });
  3224. this.Hat.belongsToMany(this.Individual, {
  3225. through: this.Event,
  3226. as: {
  3227. singular: 'hatwornby',
  3228. plural: 'hatwornbys',
  3229. },
  3230. });
  3231. });
  3232. it('should load with an alias', async function () {
  3233. await this.sequelize.sync({ force: true });
  3234. const [individual0, hat0] = await Promise.all([
  3235. this.Individual.create({ name: 'Foo Bar' }),
  3236. this.Hat.create({ name: 'Baz' }),
  3237. ]);
  3238. await individual0.addPersonwearinghat(hat0);
  3239. const individual = await this.Individual.findOne({
  3240. where: { name: 'Foo Bar' },
  3241. include: [{ model: this.Hat, as: 'personwearinghats' }],
  3242. });
  3243. expect(individual.name).to.equal('Foo Bar');
  3244. expect(individual.personwearinghats.length).to.equal(1);
  3245. expect(individual.personwearinghats[0].name).to.equal('Baz');
  3246. const hat = await this.Hat.findOne({
  3247. where: { name: 'Baz' },
  3248. include: [{ model: this.Individual, as: 'hatwornbys' }],
  3249. });
  3250. expect(hat.name).to.equal('Baz');
  3251. expect(hat.hatwornbys.length).to.equal(1);
  3252. expect(hat.hatwornbys[0].name).to.equal('Foo Bar');
  3253. });
  3254. it('should load all', async function () {
  3255. await this.sequelize.sync({ force: true });
  3256. const [individual0, hat0] = await Promise.all([
  3257. this.Individual.create({ name: 'Foo Bar' }),
  3258. this.Hat.create({ name: 'Baz' }),
  3259. ]);
  3260. await individual0.addPersonwearinghat(hat0);
  3261. const individual = await this.Individual.findOne({
  3262. where: { name: 'Foo Bar' },
  3263. include: [{ all: true }],
  3264. });
  3265. expect(individual.name).to.equal('Foo Bar');
  3266. expect(individual.personwearinghats.length).to.equal(1);
  3267. expect(individual.personwearinghats[0].name).to.equal('Baz');
  3268. const hat = await this.Hat.findOne({
  3269. where: { name: 'Baz' },
  3270. include: [{ all: true }],
  3271. });
  3272. expect(hat.name).to.equal('Baz');
  3273. expect(hat.hatwornbys.length).to.equal(1);
  3274. expect(hat.hatwornbys[0].name).to.equal('Foo Bar');
  3275. });
  3276. });
  3277. describe('Disabling default unique constraint', () => {
  3278. beforeEach(function () {
  3279. this.Order = this.sequelize.define('order', {});
  3280. this.Good = this.sequelize.define('good', {
  3281. name: DataTypes.STRING,
  3282. });
  3283. this.OrderItem = this.sequelize.define('orderitem', {
  3284. id: {
  3285. type: DataTypes.INTEGER,
  3286. primaryKey: true,
  3287. autoIncrement: true,
  3288. },
  3289. isUpsell: {
  3290. type: DataTypes.BOOLEAN,
  3291. defaultValue: false,
  3292. },
  3293. });
  3294. this.Order.belongsToMany(this.Good, {
  3295. through: {
  3296. model: this.OrderItem,
  3297. unique: false,
  3298. },
  3299. });
  3300. this.Good.belongsToMany(this.Order, {
  3301. through: {
  3302. model: this.OrderItem,
  3303. unique: false,
  3304. },
  3305. });
  3306. });
  3307. it('should create new relations in parallel', async function () {
  3308. await this.sequelize.sync({ force: true });
  3309. const { Good, Order } = this;
  3310. const order = await Order.create();
  3311. const good = await Good.create({ name: 'Drink' });
  3312. await Promise.all([
  3313. order.addGood(good, {
  3314. through: {
  3315. isUpsell: false,
  3316. },
  3317. }),
  3318. order.addGood(good, {
  3319. through: {
  3320. isUpsell: true,
  3321. },
  3322. }),
  3323. ]);
  3324. const orderGoods = await order.getGoods();
  3325. const [firstGood, secondGood] = orderGoods;
  3326. expect(orderGoods.length).to.equal(2);
  3327. expect(firstGood.orderGood.isUpsell).to.be.not.equal(secondGood.orderGood.isUpsell);
  3328. });
  3329. it('should create new relations sequentialy', async function () {
  3330. await this.sequelize.sync({ force: true });
  3331. const { Good, Order } = this;
  3332. const order = await Order.create();
  3333. const good = await Good.create({ name: 'Drink' });
  3334. await order.addGood(good, {
  3335. through: {
  3336. isUpsell: false,
  3337. },
  3338. });
  3339. await order.addGood(good, {
  3340. through: {
  3341. isUpsell: true,
  3342. },
  3343. });
  3344. const orderGoods = await order.getGoods();
  3345. const [firstGood, secondGood] = orderGoods;
  3346. expect(orderGoods.length).to.equal(2);
  3347. expect(firstGood.orderGood.isUpsell).to.be.not.equal(secondGood.orderGood.isUpsell);
  3348. });
  3349. });
  3350. });