@athenna/database
Version:
The Athenna database handler for SQL/NoSQL.
41 lines (40 loc) • 1.26 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 HasOneRelation {
/**
* Load a has one relation.
*/
static async load(model, relation) {
model[relation.property] = await relation
.model()
.query()
.where(relation.foreignKey, model[relation.primaryKey])
.when(relation.closure, relation.closure)
.find();
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 => map.set(result[relation.foreignKey], result));
return models.map(model => {
model[relation.property] = map.get(model[relation.primaryKey]);
return model;
});
}
}