@athenna/database
Version:
The Athenna database handler for SQL/NoSQL.
67 lines (66 loc) • 2.52 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.
*/
import { String } from '@athenna/common';
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.withClosure, relation.withClosure)
.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.withClosure, relation.withClosure)
.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;
});
}
/**
* Apply a where has relation to the query when the given model
* has one of the relation.
*/
static whereHas(Model, query, relation) {
const RelationModel = relation.model();
const modelSchema = Model.schema();
const relationSchema = RelationModel.schema();
const primaryKey = relation.primaryKey
? modelSchema.getColumnNameByProperty(relation.primaryKey)
: modelSchema.getMainPrimaryKeyName();
const foreignKey = relation.foreignKey
? relationSchema.getColumnNameByProperty(relation.foreignKey)
: relationSchema.getColumnNameByProperty(`${String.toCamelCase(Model.name)}Id`);
let whereRaw = `${RelationModel.table()}.${foreignKey} = ${Model.table()}.${primaryKey}`;
switch (RelationModel.schema().getModelDriverName()) {
case 'sqlite':
case 'postgres':
whereRaw = `"${RelationModel.table()}"."${foreignKey}" = "${Model.table()}"."${primaryKey}"`;
}
RelationModel.query()
.setDriver(query, RelationModel.table())
.whereRaw(whereRaw)
.when(relation.closure, relation.closure);
}
}