belongs-to-many.js 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823
  1. 'use strict';
  2. const Utils = require('./../utils');
  3. const Helpers = require('./helpers');
  4. const _ = require('lodash');
  5. const Association = require('./base');
  6. const BelongsTo = require('./belongs-to');
  7. const HasMany = require('./has-many');
  8. const HasOne = require('./has-one');
  9. const AssociationError = require('../errors').AssociationError;
  10. const EmptyResultError = require('../errors').EmptyResultError;
  11. const Op = require('../operators');
  12. /**
  13. * Many-to-many association with a join table.
  14. *
  15. * When the join table has additional attributes, these can be passed in the options object:
  16. *
  17. * ```js
  18. * UserProject = sequelize.define('user_project', {
  19. * role: Sequelize.STRING
  20. * });
  21. * User.belongsToMany(Project, { through: UserProject });
  22. * Project.belongsToMany(User, { through: UserProject });
  23. * // through is required!
  24. *
  25. * user.addProject(project, { through: { role: 'manager' }});
  26. * ```
  27. *
  28. * All methods allow you to pass either a persisted instance, its primary key, or a mixture:
  29. *
  30. * ```js
  31. * const project = await Project.create({ id: 11 });
  32. * await user.addProjects([project, 12]);
  33. * ```
  34. *
  35. * If you want to set several target instances, but with different attributes you have to set the attributes on the instance, using a property with the name of the through model:
  36. *
  37. * ```js
  38. * p1.UserProjects = {
  39. * started: true
  40. * }
  41. * user.setProjects([p1, p2], { through: { started: false }}) // The default value is false, but p1 overrides that.
  42. * ```
  43. *
  44. * Similarly, when fetching through a join table with custom attributes, these attributes will be available as an object with the name of the through model.
  45. * ```js
  46. * const projects = await user.getProjects();
  47. * const p1 = projects[0];
  48. * p1.UserProjects.started // Is this project started yet?
  49. * })
  50. * ```
  51. *
  52. * In the API reference below, add the name of the association to the method, e.g. for `User.belongsToMany(Project)` the getter will be `user.getProjects()`.
  53. *
  54. * @see {@link Model.belongsToMany}
  55. */
  56. class BelongsToMany extends Association {
  57. constructor(source, target, options) {
  58. super(source, target, options);
  59. if (this.options.through === undefined || this.options.through === true || this.options.through === null) {
  60. throw new AssociationError(`${source.name}.belongsToMany(${target.name}) requires through option, pass either a string or a model`);
  61. }
  62. if (!this.options.through.model) {
  63. this.options.through = {
  64. model: options.through
  65. };
  66. }
  67. this.associationType = 'BelongsToMany';
  68. this.targetAssociation = null;
  69. this.sequelize = source.sequelize;
  70. this.through = { ...this.options.through };
  71. this.isMultiAssociation = true;
  72. this.doubleLinked = false;
  73. if (!this.as && this.isSelfAssociation) {
  74. throw new AssociationError('\'as\' must be defined for many-to-many self-associations');
  75. }
  76. if (this.as) {
  77. this.isAliased = true;
  78. if (_.isPlainObject(this.as)) {
  79. this.options.name = this.as;
  80. this.as = this.as.plural;
  81. } else {
  82. this.options.name = {
  83. plural: this.as,
  84. singular: Utils.singularize(this.as)
  85. };
  86. }
  87. } else {
  88. this.as = this.target.options.name.plural;
  89. this.options.name = this.target.options.name;
  90. }
  91. this.combinedTableName = Utils.combineTableNames(
  92. this.source.tableName,
  93. this.isSelfAssociation ? this.as || this.target.tableName : this.target.tableName
  94. );
  95. /*
  96. * If self association, this is the target association - Unless we find a pairing association
  97. */
  98. if (this.isSelfAssociation) {
  99. this.targetAssociation = this;
  100. }
  101. /*
  102. * Find paired association (if exists)
  103. */
  104. _.each(this.target.associations, association => {
  105. if (association.associationType !== 'BelongsToMany') return;
  106. if (association.target !== this.source) return;
  107. if (this.options.through.model === association.options.through.model) {
  108. this.paired = association;
  109. association.paired = this;
  110. }
  111. });
  112. /*
  113. * Default/generated source/target keys
  114. */
  115. this.sourceKey = this.options.sourceKey || this.source.primaryKeyAttribute;
  116. this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;
  117. if (this.options.targetKey) {
  118. this.targetKey = this.options.targetKey;
  119. this.targetKeyField = this.target.rawAttributes[this.targetKey].field || this.targetKey;
  120. } else {
  121. this.targetKeyDefault = true;
  122. this.targetKey = this.target.primaryKeyAttribute;
  123. this.targetKeyField = this.target.rawAttributes[this.targetKey].field || this.targetKey;
  124. }
  125. this._createForeignAndOtherKeys();
  126. if (typeof this.through.model === 'string') {
  127. if (!this.sequelize.isDefined(this.through.model)) {
  128. this.through.model = this.sequelize.define(this.through.model, {}, Object.assign(this.options, {
  129. tableName: this.through.model,
  130. indexes: [], //we don't want indexes here (as referenced in #2416)
  131. paranoid: this.through.paranoid ? this.through.paranoid : false, // Default to non-paranoid join (referenced in #11991)
  132. validate: {} // Don't propagate model-level validations
  133. }));
  134. } else {
  135. this.through.model = this.sequelize.model(this.through.model);
  136. }
  137. }
  138. Object.assign(this.options, _.pick(this.through.model.options, [
  139. 'timestamps', 'createdAt', 'updatedAt', 'deletedAt', 'paranoid'
  140. ]));
  141. if (this.paired) {
  142. let needInjectPaired = false;
  143. if (this.targetKeyDefault) {
  144. this.targetKey = this.paired.sourceKey;
  145. this.targetKeyField = this.paired.sourceKeyField;
  146. this._createForeignAndOtherKeys();
  147. }
  148. if (this.paired.targetKeyDefault) {
  149. // in this case paired.otherKey depends on paired.targetKey,
  150. // so cleanup previously wrong generated otherKey
  151. if (this.paired.targetKey !== this.sourceKey) {
  152. delete this.through.model.rawAttributes[this.paired.otherKey];
  153. this.paired.targetKey = this.sourceKey;
  154. this.paired.targetKeyField = this.sourceKeyField;
  155. this.paired._createForeignAndOtherKeys();
  156. needInjectPaired = true;
  157. }
  158. }
  159. if (this.otherKeyDefault) {
  160. this.otherKey = this.paired.foreignKey;
  161. }
  162. if (this.paired.otherKeyDefault) {
  163. // If paired otherKey was inferred we should make sure to clean it up
  164. // before adding a new one that matches the foreignKey
  165. if (this.paired.otherKey !== this.foreignKey) {
  166. delete this.through.model.rawAttributes[this.paired.otherKey];
  167. this.paired.otherKey = this.foreignKey;
  168. needInjectPaired = true;
  169. }
  170. }
  171. if (needInjectPaired) {
  172. this.paired._injectAttributes();
  173. }
  174. }
  175. if (this.through) {
  176. this.throughModel = this.through.model;
  177. }
  178. this.options.tableName = this.combinedName = this.through.model === Object(this.through.model) ? this.through.model.tableName : this.through.model;
  179. this.associationAccessor = this.as;
  180. // Get singular and plural names, trying to uppercase the first letter, unless the model forbids it
  181. const plural = _.upperFirst(this.options.name.plural);
  182. const singular = _.upperFirst(this.options.name.singular);
  183. this.accessors = {
  184. get: `get${plural}`,
  185. set: `set${plural}`,
  186. addMultiple: `add${plural}`,
  187. add: `add${singular}`,
  188. create: `create${singular}`,
  189. remove: `remove${singular}`,
  190. removeMultiple: `remove${plural}`,
  191. hasSingle: `has${singular}`,
  192. hasAll: `has${plural}`,
  193. count: `count${plural}`
  194. };
  195. }
  196. _createForeignAndOtherKeys() {
  197. /*
  198. * Default/generated foreign/other keys
  199. */
  200. if (_.isObject(this.options.foreignKey)) {
  201. this.foreignKeyAttribute = this.options.foreignKey;
  202. this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
  203. } else {
  204. this.foreignKeyAttribute = {};
  205. this.foreignKey = this.options.foreignKey || Utils.camelize(
  206. [
  207. this.source.options.name.singular,
  208. this.sourceKey
  209. ].join('_')
  210. );
  211. }
  212. if (_.isObject(this.options.otherKey)) {
  213. this.otherKeyAttribute = this.options.otherKey;
  214. this.otherKey = this.otherKeyAttribute.name || this.otherKeyAttribute.fieldName;
  215. } else {
  216. if (!this.options.otherKey) {
  217. this.otherKeyDefault = true;
  218. }
  219. this.otherKeyAttribute = {};
  220. this.otherKey = this.options.otherKey || Utils.camelize(
  221. [
  222. this.isSelfAssociation ? Utils.singularize(this.as) : this.target.options.name.singular,
  223. this.targetKey
  224. ].join('_')
  225. );
  226. }
  227. }
  228. // the id is in the target table
  229. // or in an extra table which connects two tables
  230. _injectAttributes() {
  231. this.identifier = this.foreignKey;
  232. this.foreignIdentifier = this.otherKey;
  233. // remove any PKs previously defined by sequelize
  234. // but ignore any keys that are part of this association (#5865)
  235. _.each(this.through.model.rawAttributes, (attribute, attributeName) => {
  236. if (attribute.primaryKey === true && attribute._autoGenerated === true) {
  237. if (attributeName === this.foreignKey || attributeName === this.otherKey) {
  238. // this key is still needed as it's part of the association
  239. // so just set primaryKey to false
  240. attribute.primaryKey = false;
  241. }
  242. else {
  243. delete this.through.model.rawAttributes[attributeName];
  244. }
  245. this.primaryKeyDeleted = true;
  246. }
  247. });
  248. const sourceKey = this.source.rawAttributes[this.sourceKey];
  249. const sourceKeyType = sourceKey.type;
  250. const sourceKeyField = this.sourceKeyField;
  251. const targetKey = this.target.rawAttributes[this.targetKey];
  252. const targetKeyType = targetKey.type;
  253. const targetKeyField = this.targetKeyField;
  254. const sourceAttribute = { type: sourceKeyType, ...this.foreignKeyAttribute };
  255. const targetAttribute = { type: targetKeyType, ...this.otherKeyAttribute };
  256. if (this.primaryKeyDeleted === true) {
  257. targetAttribute.primaryKey = sourceAttribute.primaryKey = true;
  258. } else if (this.through.unique !== false) {
  259. let uniqueKey;
  260. if (typeof this.options.uniqueKey === 'string' && this.options.uniqueKey !== '') {
  261. uniqueKey = this.options.uniqueKey;
  262. } else {
  263. uniqueKey = [this.through.model.tableName, this.foreignKey, this.otherKey, 'unique'].join('_');
  264. }
  265. targetAttribute.unique = sourceAttribute.unique = uniqueKey;
  266. }
  267. if (!this.through.model.rawAttributes[this.foreignKey]) {
  268. this.through.model.rawAttributes[this.foreignKey] = {
  269. _autoGenerated: true
  270. };
  271. }
  272. if (!this.through.model.rawAttributes[this.otherKey]) {
  273. this.through.model.rawAttributes[this.otherKey] = {
  274. _autoGenerated: true
  275. };
  276. }
  277. if (this.options.constraints !== false) {
  278. sourceAttribute.references = {
  279. model: this.source.getTableName(),
  280. key: sourceKeyField
  281. };
  282. // For the source attribute the passed option is the priority
  283. sourceAttribute.onDelete = this.options.onDelete || this.through.model.rawAttributes[this.foreignKey].onDelete;
  284. sourceAttribute.onUpdate = this.options.onUpdate || this.through.model.rawAttributes[this.foreignKey].onUpdate;
  285. if (!sourceAttribute.onDelete) sourceAttribute.onDelete = 'CASCADE';
  286. if (!sourceAttribute.onUpdate) sourceAttribute.onUpdate = 'CASCADE';
  287. targetAttribute.references = {
  288. model: this.target.getTableName(),
  289. key: targetKeyField
  290. };
  291. // But the for target attribute the previously defined option is the priority (since it could've been set by another belongsToMany call)
  292. targetAttribute.onDelete = this.through.model.rawAttributes[this.otherKey].onDelete || this.options.onDelete;
  293. targetAttribute.onUpdate = this.through.model.rawAttributes[this.otherKey].onUpdate || this.options.onUpdate;
  294. if (!targetAttribute.onDelete) targetAttribute.onDelete = 'CASCADE';
  295. if (!targetAttribute.onUpdate) targetAttribute.onUpdate = 'CASCADE';
  296. }
  297. Object.assign(this.through.model.rawAttributes[this.foreignKey], sourceAttribute);
  298. Object.assign(this.through.model.rawAttributes[this.otherKey], targetAttribute);
  299. this.through.model.refreshAttributes();
  300. this.identifierField = this.through.model.rawAttributes[this.foreignKey].field || this.foreignKey;
  301. this.foreignIdentifierField = this.through.model.rawAttributes[this.otherKey].field || this.otherKey;
  302. if (this.paired && !this.paired.foreignIdentifierField) {
  303. this.paired.foreignIdentifierField = this.through.model.rawAttributes[this.paired.otherKey].field || this.paired.otherKey;
  304. }
  305. this.toSource = new BelongsTo(this.through.model, this.source, {
  306. foreignKey: this.foreignKey
  307. });
  308. this.manyFromSource = new HasMany(this.source, this.through.model, {
  309. foreignKey: this.foreignKey
  310. });
  311. this.oneFromSource = new HasOne(this.source, this.through.model, {
  312. foreignKey: this.foreignKey,
  313. sourceKey: this.sourceKey,
  314. as: this.through.model.name
  315. });
  316. this.toTarget = new BelongsTo(this.through.model, this.target, {
  317. foreignKey: this.otherKey
  318. });
  319. this.manyFromTarget = new HasMany(this.target, this.through.model, {
  320. foreignKey: this.otherKey
  321. });
  322. this.oneFromTarget = new HasOne(this.target, this.through.model, {
  323. foreignKey: this.otherKey,
  324. sourceKey: this.targetKey,
  325. as: this.through.model.name
  326. });
  327. if (this.paired && this.paired.otherKeyDefault) {
  328. this.paired.toTarget = new BelongsTo(this.paired.through.model, this.paired.target, {
  329. foreignKey: this.paired.otherKey
  330. });
  331. this.paired.oneFromTarget = new HasOne(this.paired.target, this.paired.through.model, {
  332. foreignKey: this.paired.otherKey,
  333. sourceKey: this.paired.targetKey,
  334. as: this.paired.through.model.name
  335. });
  336. }
  337. Helpers.checkNamingCollision(this);
  338. return this;
  339. }
  340. mixin(obj) {
  341. const methods = ['get', 'count', 'hasSingle', 'hasAll', 'set', 'add', 'addMultiple', 'remove', 'removeMultiple', 'create'];
  342. const aliases = {
  343. hasSingle: 'has',
  344. hasAll: 'has',
  345. addMultiple: 'add',
  346. removeMultiple: 'remove'
  347. };
  348. Helpers.mixinMethods(this, obj, methods, aliases);
  349. }
  350. /**
  351. * Get everything currently associated with this, using an optional where clause.
  352. *
  353. * @see
  354. * {@link Model} for a full explanation of options
  355. *
  356. * @param {Model} instance instance
  357. * @param {object} [options] find options
  358. * @param {object} [options.where] An optional where clause to limit the associated models
  359. * @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
  360. * @param {string} [options.schema] Apply a schema on the related model
  361. * @param {object} [options.through.where] An optional where clause applied to through model (join table)
  362. * @param {boolean} [options.through.paranoid=true] If true, only non-deleted records will be returned from the join table. If false, both deleted and non-deleted records will be returned. Only applies if through model is paranoid
  363. *
  364. * @returns {Promise<Array<Model>>}
  365. */
  366. async get(instance, options) {
  367. options = Utils.cloneDeep(options) || {};
  368. const through = this.through;
  369. let scopeWhere;
  370. let throughWhere;
  371. if (this.scope) {
  372. scopeWhere = { ...this.scope };
  373. }
  374. options.where = {
  375. [Op.and]: [
  376. scopeWhere,
  377. options.where
  378. ]
  379. };
  380. if (Object(through.model) === through.model) {
  381. throughWhere = {};
  382. throughWhere[this.foreignKey] = instance.get(this.sourceKey);
  383. if (through.scope) {
  384. Object.assign(throughWhere, through.scope);
  385. }
  386. //If a user pass a where on the options through options, make an "and" with the current throughWhere
  387. if (options.through && options.through.where) {
  388. throughWhere = {
  389. [Op.and]: [throughWhere, options.through.where]
  390. };
  391. }
  392. options.include = options.include || [];
  393. options.include.push({
  394. association: this.oneFromTarget,
  395. attributes: options.joinTableAttributes,
  396. required: true,
  397. paranoid: _.get(options.through, 'paranoid', true),
  398. where: throughWhere
  399. });
  400. }
  401. let model = this.target;
  402. if (Object.prototype.hasOwnProperty.call(options, 'scope')) {
  403. if (!options.scope) {
  404. model = model.unscoped();
  405. } else {
  406. model = model.scope(options.scope);
  407. }
  408. }
  409. if (Object.prototype.hasOwnProperty.call(options, 'schema')) {
  410. model = model.schema(options.schema, options.schemaDelimiter);
  411. }
  412. return model.findAll(options);
  413. }
  414. /**
  415. * Count everything currently associated with this, using an optional where clause.
  416. *
  417. * @param {Model} instance instance
  418. * @param {object} [options] find options
  419. * @param {object} [options.where] An optional where clause to limit the associated models
  420. * @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
  421. *
  422. * @returns {Promise<number>}
  423. */
  424. async count(instance, options) {
  425. const sequelize = this.target.sequelize;
  426. options = Utils.cloneDeep(options);
  427. options.attributes = [
  428. [sequelize.fn('COUNT', sequelize.col([this.target.name, this.targetKeyField].join('.'))), 'count']
  429. ];
  430. options.joinTableAttributes = [];
  431. options.raw = true;
  432. options.plain = true;
  433. const result = await this.get(instance, options);
  434. return parseInt(result.count, 10);
  435. }
  436. /**
  437. * Check if one or more instance(s) are associated with this. If a list of instances is passed, the function returns true if _all_ instances are associated
  438. *
  439. * @param {Model} sourceInstance source instance to check for an association with
  440. * @param {Model|Model[]|string[]|string|number[]|number} [instances] Can be an array of instances or their primary keys
  441. * @param {object} [options] Options passed to getAssociations
  442. *
  443. * @returns {Promise<boolean>}
  444. */
  445. async has(sourceInstance, instances, options) {
  446. if (!Array.isArray(instances)) {
  447. instances = [instances];
  448. }
  449. options = {
  450. raw: true,
  451. ...options,
  452. scope: false,
  453. attributes: [this.targetKey],
  454. joinTableAttributes: []
  455. };
  456. const instancePrimaryKeys = instances.map(instance => {
  457. if (instance instanceof this.target) {
  458. return instance.where();
  459. }
  460. return {
  461. [this.targetKey]: instance
  462. };
  463. });
  464. options.where = {
  465. [Op.and]: [
  466. { [Op.or]: instancePrimaryKeys },
  467. options.where
  468. ]
  469. };
  470. const associatedObjects = await this.get(sourceInstance, options);
  471. return _.differenceWith(instancePrimaryKeys, associatedObjects,
  472. (a, b) => _.isEqual(a[this.targetKey], b[this.targetKey])).length === 0;
  473. }
  474. /**
  475. * Set the associated models by passing an array of instances or their primary keys.
  476. * Everything that it not in the passed array will be un-associated.
  477. *
  478. * @param {Model} sourceInstance source instance to associate new instances with
  479. * @param {Model|Model[]|string[]|string|number[]|number} [newAssociatedObjects] A single instance or primary key, or a mixed array of persisted instances or primary keys
  480. * @param {object} [options] Options passed to `through.findAll`, `bulkCreate`, `update` and `destroy`
  481. * @param {object} [options.validate] Run validation for the join model
  482. * @param {object} [options.through] Additional attributes for the join table.
  483. *
  484. * @returns {Promise}
  485. */
  486. async set(sourceInstance, newAssociatedObjects, options) {
  487. options = options || {};
  488. const sourceKey = this.sourceKey;
  489. const targetKey = this.targetKey;
  490. const identifier = this.identifier;
  491. const foreignIdentifier = this.foreignIdentifier;
  492. if (newAssociatedObjects === null) {
  493. newAssociatedObjects = [];
  494. } else {
  495. newAssociatedObjects = this.toInstanceArray(newAssociatedObjects);
  496. }
  497. const where = {
  498. [identifier]: sourceInstance.get(sourceKey),
  499. ...this.through.scope
  500. };
  501. const updateAssociations = currentRows => {
  502. const obsoleteAssociations = [];
  503. const promises = [];
  504. const defaultAttributes = options.through || {};
  505. const unassociatedObjects = newAssociatedObjects.filter(obj =>
  506. !currentRows.some(currentRow => currentRow[foreignIdentifier] === obj.get(targetKey))
  507. );
  508. for (const currentRow of currentRows) {
  509. const newObj = newAssociatedObjects.find(obj => currentRow[foreignIdentifier] === obj.get(targetKey));
  510. if (!newObj) {
  511. obsoleteAssociations.push(currentRow);
  512. } else {
  513. let throughAttributes = newObj[this.through.model.name];
  514. // Quick-fix for subtle bug when using existing objects that might have the through model attached (not as an attribute object)
  515. if (throughAttributes instanceof this.through.model) {
  516. throughAttributes = {};
  517. }
  518. const attributes = { ...defaultAttributes, ...throughAttributes };
  519. if (Object.keys(attributes).length) {
  520. promises.push(
  521. this.through.model.update(attributes, Object.assign(options, {
  522. where: {
  523. [identifier]: sourceInstance.get(sourceKey),
  524. [foreignIdentifier]: newObj.get(targetKey)
  525. }
  526. }
  527. ))
  528. );
  529. }
  530. }
  531. }
  532. if (obsoleteAssociations.length > 0) {
  533. promises.push(
  534. this.through.model.destroy({
  535. ...options,
  536. where: {
  537. [identifier]: sourceInstance.get(sourceKey),
  538. [foreignIdentifier]: obsoleteAssociations.map(obsoleteAssociation => obsoleteAssociation[foreignIdentifier]),
  539. ...this.through.scope
  540. }
  541. })
  542. );
  543. }
  544. if (unassociatedObjects.length > 0) {
  545. const bulk = unassociatedObjects.map(unassociatedObject => {
  546. return {
  547. ...defaultAttributes,
  548. ...unassociatedObject[this.through.model.name],
  549. [identifier]: sourceInstance.get(sourceKey),
  550. [foreignIdentifier]: unassociatedObject.get(targetKey),
  551. ...this.through.scope
  552. };
  553. });
  554. promises.push(this.through.model.bulkCreate(bulk, { validate: true, ...options }));
  555. }
  556. return Promise.all(promises);
  557. };
  558. try {
  559. const currentRows = await this.through.model.findAll({ ...options, where, raw: true });
  560. return await updateAssociations(currentRows);
  561. } catch (error) {
  562. if (error instanceof EmptyResultError) return updateAssociations([]);
  563. throw error;
  564. }
  565. }
  566. /**
  567. * Associate one or several rows with source instance. It will not un-associate any already associated instance
  568. * that may be missing from `newInstances`.
  569. *
  570. * @param {Model} sourceInstance source instance to associate new instances with
  571. * @param {Model|Model[]|string[]|string|number[]|number} [newInstances] A single instance or primary key, or a mixed array of persisted instances or primary keys
  572. * @param {object} [options] Options passed to `through.findAll`, `bulkCreate` and `update`
  573. * @param {object} [options.validate] Run validation for the join model.
  574. * @param {object} [options.through] Additional attributes for the join table.
  575. *
  576. * @returns {Promise}
  577. */
  578. async add(sourceInstance, newInstances, options) {
  579. // If newInstances is null or undefined, no-op
  580. if (!newInstances) return Promise.resolve();
  581. options = { ...options };
  582. const association = this;
  583. const sourceKey = association.sourceKey;
  584. const targetKey = association.targetKey;
  585. const identifier = association.identifier;
  586. const foreignIdentifier = association.foreignIdentifier;
  587. const defaultAttributes = options.through || {};
  588. newInstances = association.toInstanceArray(newInstances);
  589. const where = {
  590. [identifier]: sourceInstance.get(sourceKey),
  591. [foreignIdentifier]: newInstances.map(newInstance => newInstance.get(targetKey)),
  592. ...association.through.scope
  593. };
  594. const updateAssociations = currentRows => {
  595. const promises = [];
  596. const unassociatedObjects = [];
  597. const changedAssociations = [];
  598. for (const obj of newInstances) {
  599. const existingAssociation = currentRows && currentRows.find(current => current[foreignIdentifier] === obj.get(targetKey));
  600. if (!existingAssociation) {
  601. unassociatedObjects.push(obj);
  602. } else {
  603. const throughAttributes = obj[association.through.model.name];
  604. const attributes = { ...defaultAttributes, ...throughAttributes };
  605. if (Object.keys(attributes).some(attribute => attributes[attribute] !== existingAssociation[attribute])) {
  606. changedAssociations.push(obj);
  607. }
  608. }
  609. }
  610. if (unassociatedObjects.length > 0) {
  611. const bulk = unassociatedObjects.map(unassociatedObject => {
  612. const throughAttributes = unassociatedObject[association.through.model.name];
  613. const attributes = { ...defaultAttributes, ...throughAttributes };
  614. attributes[identifier] = sourceInstance.get(sourceKey);
  615. attributes[foreignIdentifier] = unassociatedObject.get(targetKey);
  616. Object.assign(attributes, association.through.scope);
  617. return attributes;
  618. });
  619. promises.push(association.through.model.bulkCreate(bulk, { validate: true, ...options }));
  620. }
  621. for (const assoc of changedAssociations) {
  622. let throughAttributes = assoc[association.through.model.name];
  623. const attributes = { ...defaultAttributes, ...throughAttributes };
  624. // Quick-fix for subtle bug when using existing objects that might have the through model attached (not as an attribute object)
  625. if (throughAttributes instanceof association.through.model) {
  626. throughAttributes = {};
  627. }
  628. promises.push(association.through.model.update(attributes, Object.assign(options, { where: {
  629. [identifier]: sourceInstance.get(sourceKey),
  630. [foreignIdentifier]: assoc.get(targetKey)
  631. } })));
  632. }
  633. return Promise.all(promises);
  634. };
  635. try {
  636. const currentRows = await association.through.model.findAll({ ...options, where, raw: true });
  637. const [associations] = await updateAssociations(currentRows);
  638. return associations;
  639. } catch (error) {
  640. if (error instanceof EmptyResultError) return updateAssociations();
  641. throw error;
  642. }
  643. }
  644. /**
  645. * Un-associate one or more instance(s).
  646. *
  647. * @param {Model} sourceInstance instance to un associate instances with
  648. * @param {Model|Model[]|string|string[]|number|number[]} [oldAssociatedObjects] Can be an Instance or its primary key, or a mixed array of instances and primary keys
  649. * @param {object} [options] Options passed to `through.destroy`
  650. *
  651. * @returns {Promise}
  652. */
  653. remove(sourceInstance, oldAssociatedObjects, options) {
  654. const association = this;
  655. options = options || {};
  656. oldAssociatedObjects = association.toInstanceArray(oldAssociatedObjects);
  657. const where = {
  658. [association.identifier]: sourceInstance.get(association.sourceKey),
  659. [association.foreignIdentifier]: oldAssociatedObjects.map(newInstance => newInstance.get(association.targetKey))
  660. };
  661. return association.through.model.destroy({ ...options, where });
  662. }
  663. /**
  664. * Create a new instance of the associated model and associate it with this.
  665. *
  666. * @param {Model} sourceInstance source instance
  667. * @param {object} [values] values for target model
  668. * @param {object} [options] Options passed to create and add
  669. * @param {object} [options.through] Additional attributes for the join table
  670. *
  671. * @returns {Promise}
  672. */
  673. async create(sourceInstance, values, options) {
  674. const association = this;
  675. options = options || {};
  676. values = values || {};
  677. if (Array.isArray(options)) {
  678. options = {
  679. fields: options
  680. };
  681. }
  682. if (association.scope) {
  683. Object.assign(values, association.scope);
  684. if (options.fields) {
  685. options.fields = options.fields.concat(Object.keys(association.scope));
  686. }
  687. }
  688. // Create the related model instance
  689. const newAssociatedObject = await association.target.create(values, options);
  690. await sourceInstance[association.accessors.add](newAssociatedObject, _.omit(options, ['fields']));
  691. return newAssociatedObject;
  692. }
  693. verifyAssociationAlias(alias) {
  694. if (typeof alias === 'string') {
  695. return this.as === alias;
  696. }
  697. if (alias && alias.plural) {
  698. return this.as === alias.plural;
  699. }
  700. return !this.isAliased;
  701. }
  702. }
  703. module.exports = BelongsToMany;
  704. module.exports.BelongsToMany = BelongsToMany;
  705. module.exports.default = BelongsToMany;