UNPKG

mevn-orm

Version:
36 lines (35 loc) 1.61 kB
import { BelongsToRelation, HasManyRelation, HasOneRelation, } from './relation.js'; /** Builds relationship methods that run against the active Knex instance. */ const createRelationshipMethods = (getDB) => ({ hasOne(Related, localKey, foreignKey) { const table = new Related().table; const keyValue = localKey ?? this.id; const relationKey = foreignKey ?? `${this.modelName}_id`; if (keyValue === undefined) { return new HasOneRelation(Related, null); } const query = getDB()(table).where({ [relationKey]: keyValue }); return new HasOneRelation(Related, query); }, hasMany(Related, localKey, foreignKey) { const table = new Related().table; const keyValue = localKey ?? this.id; const relationKey = foreignKey ?? `${this.modelName}_id`; if (keyValue === undefined) { return new HasManyRelation(Related, null); } const query = getDB()(table).where({ [relationKey]: keyValue }); return new HasManyRelation(Related, query); }, belongsTo(Related, foreignKey, ownerKey = 'id') { const table = new Related().table; const relationKey = foreignKey ?? `${new Related().modelName}_id`; const relationValue = this[relationKey]; if (relationValue === undefined || relationValue === null) { return new BelongsToRelation(Related, null); } const query = getDB()(table).where({ [ownerKey]: relationValue }); return new BelongsToRelation(Related, query); }, }); export { createRelationshipMethods };