* Registers has-many association defined by given key on given model, * defines getters / setters for associated records and associated records' ids, * adds methods for creating unsaved child records and creating saved ones * * @method addMethodsToModelClass * @param {Function} ModelC
(ModelClass, key)
| 70 | * @public |
| 71 | */ |
| 72 | addMethodsToModelClass(ModelClass, key) { |
| 73 | let modelPrototype = ModelClass.prototype; |
| 74 | let association = this; |
| 75 | let foreignKey = this.getForeignKey(); |
| 76 | let associationHash = { [key]: this }; |
| 77 | |
| 78 | modelPrototype.hasManyAssociations = Object.assign( |
| 79 | modelPrototype.hasManyAssociations, |
| 80 | associationHash |
| 81 | ); |
| 82 | |
| 83 | // update hasManyAssociationFks |
| 84 | Object.keys(modelPrototype.hasManyAssociations).forEach((key) => { |
| 85 | const value = modelPrototype.hasManyAssociations[key]; |
| 86 | modelPrototype.hasManyAssociationFks[value.getForeignKey()] = value; |
| 87 | }); |
| 88 | |
| 89 | // Add to target's dependent associations array |
| 90 | this.schema.addDependentAssociation(this, this.modelName); |
| 91 | |
| 92 | // TODO: look how this is used. Are these necessary, seems like they could be gotten from the above? |
| 93 | // Or we could use a single data structure to store this information? |
| 94 | modelPrototype.associationKeys.add(key); |
| 95 | modelPrototype.associationIdKeys.add(foreignKey); |
| 96 | |
| 97 | Object.defineProperty(modelPrototype, foreignKey, { |
| 98 | /* |
| 99 | object.childrenIds |
| 100 | - returns an array of the associated children's ids |
| 101 | */ |
| 102 | get() { |
| 103 | this._tempAssociations = this._tempAssociations || {}; |
| 104 | let tempChildren = this._tempAssociations[key]; |
| 105 | let ids = []; |
| 106 | |
| 107 | if (tempChildren) { |
| 108 | if (association.isPolymorphic) { |
| 109 | ids = tempChildren.models.map((model) => ({ |
| 110 | type: model.modelName, |
| 111 | id: model.id, |
| 112 | })); |
| 113 | } else { |
| 114 | ids = tempChildren.models.map((model) => model.id); |
| 115 | } |
| 116 | } else { |
| 117 | ids = this.attrs[foreignKey] || []; |
| 118 | } |
| 119 | |
| 120 | return ids; |
| 121 | }, |
| 122 | |
| 123 | /* |
| 124 | object.childrenIds = ([childrenIds...]) |
| 125 | - sets the associated children (via id) |
| 126 | */ |
| 127 | set(ids) { |
| 128 | let tempChildren; |
| 129 |
no test coverage detected