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