belongs-to-many.js 28 KB

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