has-one.js 8.3 KB

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