* Get the associated instance. * * @param {Model|Array<Model>} instances source instances * @param {object} [options] find options * @param {string|boolean} [options.scope] Apply a scope on the related model, or remove its default scope by passing false * @param {string} [opti
(instances, options)
| 124 | * @returns {Promise<Model>} |
| 125 | */ |
| 126 | async get(instances, options) { |
| 127 | const where = {}; |
| 128 | |
| 129 | let Target = this.target; |
| 130 | let instance; |
| 131 | |
| 132 | options = Utils.cloneDeep(options); |
| 133 | |
| 134 | if (Object.prototype.hasOwnProperty.call(options, 'scope')) { |
| 135 | if (!options.scope) { |
| 136 | Target = Target.unscoped(); |
| 137 | } else { |
| 138 | Target = Target.scope(options.scope); |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | if (Object.prototype.hasOwnProperty.call(options, 'schema')) { |
| 143 | Target = Target.schema(options.schema, options.schemaDelimiter); |
| 144 | } |
| 145 | |
| 146 | if (!Array.isArray(instances)) { |
| 147 | instance = instances; |
| 148 | instances = undefined; |
| 149 | } |
| 150 | |
| 151 | if (instances) { |
| 152 | where[this.foreignKey] = { |
| 153 | [Op.in]: instances.map(_instance => _instance.get(this.sourceKey)) |
| 154 | }; |
| 155 | } else { |
| 156 | where[this.foreignKey] = instance.get(this.sourceKey); |
| 157 | } |
| 158 | |
| 159 | if (this.scope) { |
| 160 | Object.assign(where, this.scope); |
| 161 | } |
| 162 | |
| 163 | options.where = options.where ? |
| 164 | { [Op.and]: [where, options.where] } : |
| 165 | where; |
| 166 | |
| 167 | if (instances) { |
| 168 | const results = await Target.findAll(options); |
| 169 | const result = {}; |
| 170 | for (const _instance of instances) { |
| 171 | result[_instance.get(this.sourceKey, { raw: true })] = null; |
| 172 | } |
| 173 | |
| 174 | for (const _instance of results) { |
| 175 | result[_instance.get(this.foreignKey, { raw: true })] = _instance; |
| 176 | } |
| 177 | |
| 178 | return result; |
| 179 | } |
| 180 | |
| 181 | return Target.findOne(options); |
| 182 | } |
| 183 |