belongs-to.js 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  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-one association
  9. *
  10. * In the API reference below, add the name of the association to the method, e.g. for `User.belongsTo(Project)` the getter will be `user.getProject()`.
  11. *
  12. * @see {@link Model.belongsTo}
  13. */
  14. class BelongsTo extends Association {
  15. constructor(source, target, options) {
  16. super(source, target, options);
  17. this.associationType = 'BelongsTo';
  18. this.isSingleAssociation = true;
  19. this.foreignKeyAttribute = {};
  20. if (this.as) {
  21. this.isAliased = true;
  22. this.options.name = {
  23. singular: this.as
  24. };
  25. } else {
  26. this.as = this.target.options.name.singular;
  27. this.options.name = this.target.options.name;
  28. }
  29. if (_.isObject(this.options.foreignKey)) {
  30. this.foreignKeyAttribute = this.options.foreignKey;
  31. this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
  32. } else if (this.options.foreignKey) {
  33. this.foreignKey = this.options.foreignKey;
  34. }
  35. if (!this.foreignKey) {
  36. this.foreignKey = Utils.camelize(
  37. [
  38. this.as,
  39. this.target.primaryKeyAttribute
  40. ].join('_')
  41. );
  42. }
  43. this.identifier = this.foreignKey;
  44. if (this.source.rawAttributes[this.identifier]) {
  45. this.identifierField = this.source.rawAttributes[this.identifier].field || this.identifier;
  46. }
  47. if (
  48. this.options.targetKey
  49. && !this.target.rawAttributes[this.options.targetKey]
  50. ) {
  51. throw new Error(`Unknown attribute "${this.options.targetKey}" passed as targetKey, define this attribute on model "${this.target.name}" first`);
  52. }
  53. this.targetKey = this.options.targetKey || this.target.primaryKeyAttribute;
  54. this.targetKeyField = this.target.rawAttributes[this.targetKey].field || this.targetKey;
  55. this.targetKeyIsPrimary = this.targetKey === this.target.primaryKeyAttribute;
  56. this.targetIdentifier = this.targetKey;
  57. this.associationAccessor = this.as;
  58. this.options.useHooks = options.useHooks;
  59. // Get singular name, trying to uppercase the first letter, unless the model forbids it
  60. const singular = _.upperFirst(this.options.name.singular);
  61. this.accessors = {
  62. get: `get${singular}`,
  63. set: `set${singular}`,
  64. create: `create${singular}`
  65. };
  66. }
  67. // the id is in the source table
  68. _injectAttributes() {
  69. const newAttributes = {
  70. [this.foreignKey]: {
  71. type: this.options.keyType || this.target.rawAttributes[this.targetKey].type,
  72. allowNull: true,
  73. ...this.foreignKeyAttribute
  74. }
  75. };
  76. if (this.options.constraints !== false) {
  77. const source = this.source.rawAttributes[this.foreignKey] || newAttributes[this.foreignKey];
  78. this.options.onDelete = this.options.onDelete || (source.allowNull ? 'SET NULL' : 'NO ACTION');
  79. this.options.onUpdate = this.options.onUpdate || 'CASCADE';
  80. }
  81. Helpers.addForeignKeyConstraints(newAttributes[this.foreignKey], this.target, this.source, this.options, this.targetKeyField);
  82. Utils.mergeDefaults(this.source.rawAttributes, newAttributes);
  83. this.source.refreshAttributes();
  84. this.identifierField = this.source.rawAttributes[this.foreignKey].field || this.foreignKey;
  85. Helpers.checkNamingCollision(this);
  86. return this;
  87. }
  88. mixin(obj) {
  89. const methods = ['get', 'set', 'create'];
  90. Helpers.mixinMethods(this, obj, methods);
  91. }
  92. /**
  93. * Get the associated instance.
  94. *
  95. * @param {Model|Array<Model>} instances source instances
  96. * @param {object} [options] find options
  97. * @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false.
  98. * @param {string} [options.schema] Apply a schema on the related model
  99. *
  100. * @see
  101. * {@link Model.findOne} for a full explanation of options
  102. *
  103. * @returns {Promise<Model>}
  104. */
  105. async get(instances, options) {
  106. const where = {};
  107. let Target = this.target;
  108. let instance;
  109. options = Utils.cloneDeep(options);
  110. if (Object.prototype.hasOwnProperty.call(options, 'scope')) {
  111. if (!options.scope) {
  112. Target = Target.unscoped();
  113. } else {
  114. Target = Target.scope(options.scope);
  115. }
  116. }
  117. if (Object.prototype.hasOwnProperty.call(options, 'schema')) {
  118. Target = Target.schema(options.schema, options.schemaDelimiter);
  119. }
  120. if (!Array.isArray(instances)) {
  121. instance = instances;
  122. instances = undefined;
  123. }
  124. if (instances) {
  125. where[this.targetKey] = {
  126. [Op.in]: instances.map(_instance => _instance.get(this.foreignKey))
  127. };
  128. } else {
  129. if (this.targetKeyIsPrimary && !options.where) {
  130. return Target.findByPk(instance.get(this.foreignKey), options);
  131. }
  132. where[this.targetKey] = instance.get(this.foreignKey);
  133. options.limit = null;
  134. }
  135. options.where = options.where ?
  136. { [Op.and]: [where, options.where] } :
  137. where;
  138. if (instances) {
  139. const results = await Target.findAll(options);
  140. const result = {};
  141. for (const _instance of instances) {
  142. result[_instance.get(this.foreignKey, { raw: true })] = null;
  143. }
  144. for (const _instance of results) {
  145. result[_instance.get(this.targetKey, { raw: true })] = _instance;
  146. }
  147. return result;
  148. }
  149. return Target.findOne(options);
  150. }
  151. /**
  152. * Set the associated model.
  153. *
  154. * @param {Model} sourceInstance the source instance
  155. * @param {?<Model>|string|number} [associatedInstance] An persisted instance or the primary key of an instance to associate with this. Pass `null` or `undefined` to remove the association.
  156. * @param {object} [options={}] options passed to `this.save`
  157. * @param {boolean} [options.save=true] Skip saving this after setting the foreign key if false.
  158. *
  159. * @returns {Promise}
  160. */
  161. async set(sourceInstance, associatedInstance, options = {}) {
  162. let value = associatedInstance;
  163. if (associatedInstance instanceof this.target) {
  164. value = associatedInstance[this.targetKey];
  165. }
  166. sourceInstance.set(this.foreignKey, value);
  167. if (options.save === false) return;
  168. options = {
  169. fields: [this.foreignKey],
  170. allowNull: [this.foreignKey],
  171. association: true,
  172. ...options
  173. };
  174. // passes the changed field to save, so only that field get updated.
  175. return await sourceInstance.save(options);
  176. }
  177. /**
  178. * Create a new instance of the associated model and associate it with this.
  179. *
  180. * @param {Model} sourceInstance the source instance
  181. * @param {object} [values={}] values to create associated model instance with
  182. * @param {object} [options={}] Options passed to `target.create` and setAssociation.
  183. *
  184. * @see
  185. * {@link Model#create} for a full explanation of options
  186. *
  187. * @returns {Promise<Model>} The created target model
  188. */
  189. async create(sourceInstance, values, options) {
  190. values = values || {};
  191. options = options || {};
  192. const newAssociatedObject = await this.target.create(values, options);
  193. await sourceInstance[this.accessors.set](newAssociatedObject, options);
  194. return newAssociatedObject;
  195. }
  196. verifyAssociationAlias(alias) {
  197. if (typeof alias === 'string') {
  198. return this.as === alias;
  199. }
  200. if (alias && alias.singular) {
  201. return this.as === alias.singular;
  202. }
  203. return !this.isAliased;
  204. }
  205. }
  206. module.exports = BelongsTo;
  207. module.exports.BelongsTo = BelongsTo;
  208. module.exports.default = BelongsTo;