has-many.js 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. 'use strict';
  2. const Utils = require('./../utils');
  3. const Helpers = require('./helpers');
  4. const _ = require('lodash');
  5. const Association = require('./base');
  6. const Op = require('../operators');
  7. /**
  8. * One-to-many association
  9. *
  10. * In the API reference below, add the name of the association to the method, e.g. for `User.hasMany(Project)` the getter will be `user.getProjects()`.
  11. * If the association is aliased, use the alias instead, e.g. `User.hasMany(Project, { as: 'jobs' })` will be `user.getJobs()`.
  12. *
  13. * @see {@link Model.hasMany}
  14. */
  15. class HasMany extends Association {
  16. constructor(source, target, options) {
  17. super(source, target, options);
  18. this.associationType = 'HasMany';
  19. this.targetAssociation = null;
  20. this.sequelize = source.sequelize;
  21. this.isMultiAssociation = true;
  22. this.foreignKeyAttribute = {};
  23. if (this.options.through) {
  24. throw new Error('N:M associations are not supported with hasMany. Use belongsToMany instead');
  25. }
  26. /*
  27. * If self association, this is the target association
  28. */
  29. if (this.isSelfAssociation) {
  30. this.targetAssociation = this;
  31. }
  32. if (this.as) {
  33. this.isAliased = true;
  34. if (_.isPlainObject(this.as)) {
  35. this.options.name = this.as;
  36. this.as = this.as.plural;
  37. } else {
  38. this.options.name = {
  39. plural: this.as,
  40. singular: Utils.singularize(this.as)
  41. };
  42. }
  43. } else {
  44. this.as = this.target.options.name.plural;
  45. this.options.name = this.target.options.name;
  46. }
  47. /*
  48. * Foreign key setup
  49. */
  50. if (_.isObject(this.options.foreignKey)) {
  51. this.foreignKeyAttribute = this.options.foreignKey;
  52. this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
  53. } else if (this.options.foreignKey) {
  54. this.foreignKey = this.options.foreignKey;
  55. }
  56. if (!this.foreignKey) {
  57. this.foreignKey = Utils.camelize(
  58. [
  59. this.source.options.name.singular,
  60. this.source.primaryKeyAttribute
  61. ].join('_')
  62. );
  63. }
  64. if (this.target.rawAttributes[this.foreignKey]) {
  65. this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
  66. this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
  67. }
  68. /*
  69. * Source key setup
  70. */
  71. this.sourceKey = this.options.sourceKey || this.source.primaryKeyAttribute;
  72. if (this.source.rawAttributes[this.sourceKey]) {
  73. this.sourceKeyAttribute = this.sourceKey;
  74. this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;
  75. } else {
  76. this.sourceKeyAttribute = this.source.primaryKeyAttribute;
  77. this.sourceKeyField = this.source.primaryKeyField;
  78. }
  79. // Get singular and plural names
  80. // try to uppercase the first letter, unless the model forbids it
  81. const plural = _.upperFirst(this.options.name.plural);
  82. const singular = _.upperFirst(this.options.name.singular);
  83. this.associationAccessor = this.as;
  84. this.accessors = {
  85. get: `get${plural}`,
  86. set: `set${plural}`,
  87. addMultiple: `add${plural}`,
  88. add: `add${singular}`,
  89. create: `create${singular}`,
  90. remove: `remove${singular}`,
  91. removeMultiple: `remove${plural}`,
  92. hasSingle: `has${singular}`,
  93. hasAll: `has${plural}`,
  94. count: `count${plural}`
  95. };
  96. }
  97. // the id is in the target table
  98. // or in an extra table which connects two tables
  99. _injectAttributes() {
  100. const newAttributes = {};
  101. // Create a new options object for use with addForeignKeyConstraints, to avoid polluting this.options in case it is later used for a n:m
  102. const constraintOptions = _.clone(this.options);
  103. newAttributes[this.foreignKey] = _.defaults({}, this.foreignKeyAttribute, {
  104. type: this.options.keyType || this.source.rawAttributes[this.sourceKeyAttribute].type,
  105. allowNull: true
  106. });
  107. if (this.options.constraints !== false) {
  108. const target = this.target.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];
  109. constraintOptions.onDelete = constraintOptions.onDelete || (target.allowNull ? 'SET NULL' : 'CASCADE');
  110. constraintOptions.onUpdate = constraintOptions.onUpdate || 'CASCADE';
  111. }
  112. Helpers.addForeignKeyConstraints(newAttributes[this.foreignKey], this.source, this.target, constraintOptions, this.sourceKeyField);
  113. Utils.mergeDefaults(this.target.rawAttributes, newAttributes);
  114. this.target.refreshAttributes();
  115. this.source.refreshAttributes();
  116. this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
  117. this.foreignKeyField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey;
  118. this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey;
  119. Helpers.checkNamingCollision(this);
  120. return this;
  121. }
  122. mixin(obj) {
  123. const methods = ['get', 'count', 'hasSingle', 'hasAll', 'set', 'add', 'addMultiple', 'remove', 'removeMultiple', 'create'];
  124. const aliases = {
  125. hasSingle: 'has',
  126. hasAll: 'has',
  127. addMultiple: 'add',
  128. removeMultiple: 'remove'
  129. };
  130. Helpers.mixinMethods(this, obj, methods, aliases);
  131. }
  132. /**
  133. * Get everything currently associated with this, using an optional where clause.
  134. *
  135. * @param {Model|Array<Model>} instances source instances
  136. * @param {Object} [options] find options
  137. * @param {Object} [options.where] An optional where clause to limit the associated models
  138. * @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
  139. * @param {string} [options.schema] Apply a schema on the related model
  140. *
  141. * @see
  142. * {@link Model.findAll} for a full explanation of options
  143. *
  144. * @returns {Promise<Array<Model>>}
  145. */
  146. get(instances, options = {}) {
  147. const where = {};
  148. let Model = this.target;
  149. let instance;
  150. let values;
  151. if (!Array.isArray(instances)) {
  152. instance = instances;
  153. instances = undefined;
  154. }
  155. options = Object.assign({}, options);
  156. if (this.scope) {
  157. Object.assign(where, this.scope);
  158. }
  159. if (instances) {
  160. values = instances.map(instance => instance.get(this.sourceKey, { raw: true }));
  161. if (options.limit && instances.length > 1) {
  162. options.groupedLimit = {
  163. limit: options.limit,
  164. on: this, // association
  165. values
  166. };
  167. delete options.limit;
  168. } else {
  169. where[this.foreignKey] = {
  170. [Op.in]: values
  171. };
  172. delete options.groupedLimit;
  173. }
  174. } else {
  175. where[this.foreignKey] = instance.get(this.sourceKey, { raw: true });
  176. }
  177. options.where = options.where ?
  178. { [Op.and]: [where, options.where] } :
  179. where;
  180. if (Object.prototype.hasOwnProperty.call(options, 'scope')) {
  181. if (!options.scope) {
  182. Model = Model.unscoped();
  183. } else {
  184. Model = Model.scope(options.scope);
  185. }
  186. }
  187. if (Object.prototype.hasOwnProperty.call(options, 'schema')) {
  188. Model = Model.schema(options.schema, options.schemaDelimiter);
  189. }
  190. return Model.findAll(options).then(results => {
  191. if (instance) return results;
  192. const result = {};
  193. for (const instance of instances) {
  194. result[instance.get(this.sourceKey, { raw: true })] = [];
  195. }
  196. for (const instance of results) {
  197. result[instance.get(this.foreignKey, { raw: true })].push(instance);
  198. }
  199. return result;
  200. });
  201. }
  202. /**
  203. * Count everything currently associated with this, using an optional where clause.
  204. *
  205. * @param {Model} instance the source instance
  206. * @param {Object} [options] find & count options
  207. * @param {Object} [options.where] An optional where clause to limit the associated models
  208. * @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false
  209. *
  210. * @returns {Promise<number>}
  211. */
  212. count(instance, options) {
  213. options = Utils.cloneDeep(options);
  214. options.attributes = [
  215. [
  216. this.sequelize.fn(
  217. 'COUNT',
  218. this.sequelize.col(`${this.target.name}.${this.target.primaryKeyField}`)
  219. ),
  220. 'count'
  221. ]
  222. ];
  223. options.raw = true;
  224. options.plain = true;
  225. return this.get(instance, options).then(result => parseInt(result.count, 10));
  226. }
  227. /**
  228. * Check if one or more rows are associated with `this`.
  229. *
  230. * @param {Model} sourceInstance the source instance
  231. * @param {Model|Model[]|string[]|string|number[]|number} [targetInstances] Can be an array of instances or their primary keys
  232. * @param {Object} [options] Options passed to getAssociations
  233. *
  234. * @returns {Promise}
  235. */
  236. has(sourceInstance, targetInstances, options) {
  237. const where = {};
  238. if (!Array.isArray(targetInstances)) {
  239. targetInstances = [targetInstances];
  240. }
  241. options = Object.assign({}, options, {
  242. scope: false,
  243. attributes: [this.target.primaryKeyAttribute],
  244. raw: true
  245. });
  246. where[Op.or] = targetInstances.map(instance => {
  247. if (instance instanceof this.target) {
  248. return instance.where();
  249. }
  250. return {
  251. [this.target.primaryKeyAttribute]: instance
  252. };
  253. });
  254. options.where = {
  255. [Op.and]: [
  256. where,
  257. options.where
  258. ]
  259. };
  260. return this.get(sourceInstance, options).then(associatedObjects => associatedObjects.length === targetInstances.length);
  261. }
  262. /**
  263. * Set the associated models by passing an array of persisted instances or their primary keys. Everything that is not in the passed array will be un-associated
  264. *
  265. * @param {Model} sourceInstance source instance to associate new instances with
  266. * @param {Model|Model[]|string[]|string|number[]|number} [targetInstances] An array of persisted instances or primary key of instances to associate with this. Pass `null` or `undefined` to remove all associations.
  267. * @param {Object} [options] Options passed to `target.findAll` and `update`.
  268. * @param {Object} [options.validate] Run validation for the join model
  269. *
  270. * @returns {Promise}
  271. */
  272. set(sourceInstance, targetInstances, options) {
  273. if (targetInstances === null) {
  274. targetInstances = [];
  275. } else {
  276. targetInstances = this.toInstanceArray(targetInstances);
  277. }
  278. return this.get(sourceInstance, _.defaults({ scope: false, raw: true }, options)).then(oldAssociations => {
  279. const promises = [];
  280. const obsoleteAssociations = oldAssociations.filter(old =>
  281. !targetInstances.find(obj =>
  282. obj[this.target.primaryKeyAttribute] === old[this.target.primaryKeyAttribute]
  283. )
  284. );
  285. const unassociatedObjects = targetInstances.filter(obj =>
  286. !oldAssociations.find(old =>
  287. obj[this.target.primaryKeyAttribute] === old[this.target.primaryKeyAttribute]
  288. )
  289. );
  290. let updateWhere;
  291. let update;
  292. if (obsoleteAssociations.length > 0) {
  293. update = {};
  294. update[this.foreignKey] = null;
  295. updateWhere = {
  296. [this.target.primaryKeyAttribute]: obsoleteAssociations.map(associatedObject =>
  297. associatedObject[this.target.primaryKeyAttribute]
  298. )
  299. };
  300. promises.push(this.target.unscoped().update(
  301. update,
  302. _.defaults({
  303. where: updateWhere
  304. }, options)
  305. ));
  306. }
  307. if (unassociatedObjects.length > 0) {
  308. updateWhere = {};
  309. update = {};
  310. update[this.foreignKey] = sourceInstance.get(this.sourceKey);
  311. Object.assign(update, this.scope);
  312. updateWhere[this.target.primaryKeyAttribute] = unassociatedObjects.map(unassociatedObject =>
  313. unassociatedObject[this.target.primaryKeyAttribute]
  314. );
  315. promises.push(this.target.unscoped().update(
  316. update,
  317. _.defaults({
  318. where: updateWhere
  319. }, options)
  320. ));
  321. }
  322. return Utils.Promise.all(promises).return(sourceInstance);
  323. });
  324. }
  325. /**
  326. * Associate one or more target rows with `this`. This method accepts a Model / string / number to associate a single row,
  327. * or a mixed array of Model / string / numbers to associate multiple rows.
  328. *
  329. * @param {Model} sourceInstance the source instance
  330. * @param {Model|Model[]|string[]|string|number[]|number} [targetInstances] A single instance or primary key, or a mixed array of persisted instances or primary keys
  331. * @param {Object} [options] Options passed to `target.update`.
  332. *
  333. * @returns {Promise}
  334. */
  335. add(sourceInstance, targetInstances, options = {}) {
  336. if (!targetInstances) return Utils.Promise.resolve();
  337. const update = {};
  338. targetInstances = this.toInstanceArray(targetInstances);
  339. update[this.foreignKey] = sourceInstance.get(this.sourceKey);
  340. Object.assign(update, this.scope);
  341. const where = {
  342. [this.target.primaryKeyAttribute]: targetInstances.map(unassociatedObject =>
  343. unassociatedObject.get(this.target.primaryKeyAttribute)
  344. )
  345. };
  346. return this.target.unscoped().update(update, _.defaults({ where }, options)).return(sourceInstance);
  347. }
  348. /**
  349. * Un-associate one or several target rows.
  350. *
  351. * @param {Model} sourceInstance instance to un associate instances with
  352. * @param {Model|Model[]|string|string[]|number|number[]} [targetInstances] Can be an Instance or its primary key, or a mixed array of instances and primary keys
  353. * @param {Object} [options] Options passed to `target.update`
  354. *
  355. * @returns {Promise}
  356. */
  357. remove(sourceInstance, targetInstances, options = {}) {
  358. const update = {
  359. [this.foreignKey]: null
  360. };
  361. targetInstances = this.toInstanceArray(targetInstances);
  362. const where = {
  363. [this.foreignKey]: sourceInstance.get(this.sourceKey),
  364. [this.target.primaryKeyAttribute]: targetInstances.map(targetInstance =>
  365. targetInstance.get(this.target.primaryKeyAttribute)
  366. )
  367. };
  368. return this.target.unscoped().update(update, _.defaults({ where }, options)).return(this);
  369. }
  370. /**
  371. * Create a new instance of the associated model and associate it with this.
  372. *
  373. * @param {Model} sourceInstance source instance
  374. * @param {Object} [values] values for target model instance
  375. * @param {Object} [options] Options passed to `target.create`
  376. *
  377. * @returns {Promise}
  378. */
  379. create(sourceInstance, values, options = {}) {
  380. if (Array.isArray(options)) {
  381. options = {
  382. fields: options
  383. };
  384. }
  385. if (values === undefined) {
  386. values = {};
  387. }
  388. if (this.scope) {
  389. for (const attribute of Object.keys(this.scope)) {
  390. values[attribute] = this.scope[attribute];
  391. if (options.fields) options.fields.push(attribute);
  392. }
  393. }
  394. values[this.foreignKey] = sourceInstance.get(this.sourceKey);
  395. if (options.fields) options.fields.push(this.foreignKey);
  396. return this.target.create(values, options);
  397. }
  398. verifyAssociationAlias(alias) {
  399. if (typeof alias === 'string') {
  400. return this.as === alias;
  401. }
  402. if (alias && alias.plural) {
  403. return this.as === alias.plural;
  404. }
  405. return !this.isAliased;
  406. }
  407. }
  408. module.exports = HasMany;
  409. module.exports.HasMany = HasMany;
  410. module.exports.default = HasMany;