* One-to-one association * * 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()`. * This is almost the same as `belongsTo` with one exception - The foreign key will be defined on the target model. * *
| 15 | * @see {@link Model.hasOne} |
| 16 | */ |
| 17 | class HasOne extends Association { |
| 18 | constructor(source, target, options) { |
| 19 | super(source, target, options); |
| 20 | |
| 21 | this.associationType = 'HasOne'; |
| 22 | this.isSingleAssociation = true; |
| 23 | this.foreignKeyAttribute = {}; |
| 24 | |
| 25 | if (this.as) { |
| 26 | this.isAliased = true; |
| 27 | this.options.name = { |
| 28 | singular: this.as |
| 29 | }; |
| 30 | } else { |
| 31 | this.as = this.target.options.name.singular; |
| 32 | this.options.name = this.target.options.name; |
| 33 | } |
| 34 | |
| 35 | if (_.isObject(this.options.foreignKey)) { |
| 36 | this.foreignKeyAttribute = this.options.foreignKey; |
| 37 | this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName; |
| 38 | } else if (this.options.foreignKey) { |
| 39 | this.foreignKey = this.options.foreignKey; |
| 40 | } |
| 41 | |
| 42 | if (!this.foreignKey) { |
| 43 | this.foreignKey = Utils.camelize( |
| 44 | [ |
| 45 | Utils.singularize(this.options.as || this.source.name), |
| 46 | this.source.primaryKeyAttribute |
| 47 | ].join('_') |
| 48 | ); |
| 49 | } |
| 50 | |
| 51 | if ( |
| 52 | this.options.sourceKey |
| 53 | && !this.source.rawAttributes[this.options.sourceKey] |
| 54 | ) { |
| 55 | throw new Error(`Unknown attribute "${this.options.sourceKey}" passed as sourceKey, define this attribute on model "${this.source.name}" first`); |
| 56 | } |
| 57 | |
| 58 | this.sourceKey = this.sourceKeyAttribute = this.options.sourceKey || this.source.primaryKeyAttribute; |
| 59 | this.sourceKeyField = this.source.rawAttributes[this.sourceKey].field || this.sourceKey; |
| 60 | this.sourceKeyIsPrimary = this.sourceKey === this.source.primaryKeyAttribute; |
| 61 | |
| 62 | this.associationAccessor = this.as; |
| 63 | this.options.useHooks = options.useHooks; |
| 64 | |
| 65 | if (this.target.rawAttributes[this.foreignKey]) { |
| 66 | this.identifierField = this.target.rawAttributes[this.foreignKey].field || this.foreignKey; |
| 67 | } |
| 68 | |
| 69 | // Get singular name, trying to uppercase the first letter, unless the model forbids it |
| 70 | const singular = _.upperFirst(this.options.name.singular); |
| 71 | |
| 72 | this.accessors = { |
| 73 | get: `get${singular}`, |
| 74 | set: `set${singular}`, |
nothing calls this directly
no outgoing calls
no test coverage detected