@athenna/database
Version:
The Athenna database handler for SQL/NoSQL.
45 lines (44 loc) • 1.39 kB
JavaScript
/**
* @athenna/database
*
* (c) João Lenon <lenon@athenna.io>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
export class HasManyRelation {
/**
* Load a has many relation.
*/
static async load(model, relation) {
model[relation.property] = await relation
.model()
.query()
.where(relation.foreignKey, model[relation.primaryKey])
.when(relation.closure, relation.closure)
.findMany();
return model;
}
/**
* Load all models that has one relation.
*/
static async loadAll(models, relation) {
const primaryValues = models.map(model => model[relation.primaryKey]);
const results = await relation
.model()
.query()
.whereIn(relation.foreignKey, primaryValues)
.when(relation.closure, relation.closure)
.findMany();
const map = new Map();
results.forEach(result => {
const array = map.get(result[relation.foreignKey]) || [];
array.push(result);
map.set(result[relation.foreignKey], array);
});
return models.map(model => {
model[relation.property] = map.get(model[relation.primaryKey]) || [];
return model;
});
}
}