fix persisting of many to many entity

This commit is contained in:
dswbx
2025-02-18 15:43:19 +01:00
parent 400db84dd5
commit f494735a79
12 changed files with 86 additions and 70 deletions

View File

@@ -165,6 +165,13 @@ export class Entity<
return this.getField(name);
}
hasField(name: string): boolean;
hasField(field: Field): boolean;
hasField(nameOrField: string | Field): boolean {
const name = typeof nameOrField === "string" ? nameOrField : nameOrField.name;
return this.fields.findIndex((field) => field.name === name) !== -1;
}
getFields(include_virtual: boolean = false): Field[] {
if (include_virtual) return this.fields;
return this.fields.filter((f) => !f.isVirtual());

View File

@@ -73,7 +73,6 @@ export class Repository<TBD extends object = DefaultDB, TB extends keyof TBD = a
sort: entity.getDefaultSort(),
select: entity.getSelect()
};
//console.log("validated", validated);
if (!options) return validated;
@@ -144,7 +143,9 @@ export class Repository<TBD extends object = DefaultDB, TB extends keyof TBD = a
});
if (invalid.length > 0) {
throw new InvalidSearchParamsException(`Invalid where field(s): ${invalid.join(", ")}`);
throw new InvalidSearchParamsException(
`Invalid where field(s): ${invalid.join(", ")}`
).context({ aliases, entity: entity.name });
}
validated.where = options.where;
@@ -334,7 +335,6 @@ export class Repository<TBD extends object = DefaultDB, TB extends keyof TBD = a
async findMany(_options?: Partial<RepoQuery>): Promise<RepositoryResponse<TBD[TB][]>> {
const { qb, options } = this.buildQuery(_options);
//console.log("findMany:options", options);
await this.emgr.emit(
new Repository.Events.RepositoryFindManyBefore({ entity: this.entity, options })
@@ -386,7 +386,6 @@ export class Repository<TBD extends object = DefaultDB, TB extends keyof TBD = a
}
};
//console.log("findManyOptions", newEntity.name, findManyOptions);
return this.cloneFor(newEntity).findMany(findManyOptions);
}

View File

@@ -37,7 +37,7 @@ export class PrimaryField<Required extends true | false = false> extends Field<
}
override async transformPersist(value: any): Promise<number> {
throw new Error("This function should not be called");
throw new Error("PrimaryField: This function should not be called");
}
override toJsonSchema() {

View File

@@ -105,13 +105,13 @@ export class ManyToManyRelation extends EntityRelation<typeof ManyToManyRelation
}
override getReferenceQuery(entity: Entity, id: number): Partial<RepoQuery> {
const conn = this.connectionEntity;
const { other, otherRef } = this.getQueryInfo(entity);
return {
where: {
[`${conn.name}.${entity.name}_${entity.getPrimaryField().name}`]: id
[otherRef]: id
},
join: [this.target.reference]
join: [other.reference]
};
}
@@ -160,47 +160,27 @@ export class ManyToManyRelation extends EntityRelation<typeof ManyToManyRelation
.whereRef(entityRef, "=", otherRef)
.innerJoin(...join)
.limit(limit);
/*return qb.select((eb) => {
const select: any[] = other.entity.getSelect(other.entity.name);
// @todo: also add to find by references
if (additionalFields.length > 0) {
const conn = this.connectionEntity.name;
select.push(
jsonBuildObject(
Object.fromEntries(
additionalFields.map((f) => [f.name, eb.ref(`${conn}.${f.name}`)])
)
).as(this.connectionTableMappedName)
);
}
return jsonFrom(
eb
.selectFrom(other.entity.name)
.select(select)
.whereRef(entityRef, "=", otherRef)
.innerJoin(...join)
.limit(limit)
).as(other.reference);
});*/
}
initialize(em: EntityManager<any>) {
this.em = em;
//this.connectionEntity.addField(new RelationField(this.source.entity));
//this.connectionEntity.addField(new RelationField(this.target.entity));
this.connectionEntity.addField(RelationField.create(this, this.source));
this.connectionEntity.addField(RelationField.create(this, this.target));
const sourceField = RelationField.create(this, this.source);
const targetField = RelationField.create(this, this.target);
// @todo: check this
for (const field of this.additionalFields) {
this.source.entity.addField(new VirtualField(this.connectionTableMappedName));
this.target.entity.addField(new VirtualField(this.connectionTableMappedName));
if (em.hasEntity(this.connectionEntity)) {
// @todo: also check for correct signatures of field
if (!this.connectionEntity.hasField(sourceField)) {
this.connectionEntity.addField(sourceField);
}
if (!this.connectionEntity.hasField(targetField)) {
this.connectionEntity.addField(targetField);
}
} else {
this.connectionEntity.addField(sourceField);
this.connectionEntity.addField(targetField);
em.addEntity(this.connectionEntity);
}
em.addEntity(this.connectionEntity);
}
override getName(): string {

View File

@@ -88,7 +88,7 @@ export class RelationField extends Field<RelationFieldConfig> {
}
override async transformPersist(value: any, em: EntityManager<any>): Promise<any> {
throw new Error("This function should not be called");
throw new Error("RelationField: This function should not be called");
}
override toJsonSchema() {

View File

@@ -2,6 +2,7 @@ import type { PrimaryFieldType } from "core";
import type { Entity, EntityManager } from "../entities";
import {
type EntityRelation,
ManyToManyRelation,
type MutationOperation,
MutationOperations,
RelationField
@@ -26,11 +27,26 @@ export class RelationMutator {
*/
getRelationalKeys(): string[] {
const references: string[] = [];
// if persisting a manytomany connection table
// @todo: improve later
if (this.entity.type === "generated") {
const relation = this.em.relations.all.find(
(r) => r instanceof ManyToManyRelation && r.connectionEntity.name === this.entity.name
);
if (relation instanceof ManyToManyRelation) {
references.push(
...this.entity.fields.filter((f) => f.type === "relation").map((f) => f.name)
);
}
}
this.em.relationsOf(this.entity.name).map((r) => {
const info = r.helper(this.entity.name).getMutationInfo();
references.push(info.reference);
info.local_field && references.push(info.local_field);
});
return references;
}