Skip to content

Handle multiple joinRelations that share identical RelationExpression #1114

@johnmaia

Description

@johnmaia

Given the following dummy entities:

father: {
  id,
  name,
  ...
}
mother: {
  id,
  name,
  ...
}
student: {
 id,
 fatherId,
 motherId,
 classId
 ...
}
class: {
 id,
 ...
}

student entity has two relations:

father: {
  join: {
    from: 'student.fatherId',
    to: 'father.id'
  },
  modelClass: Father,
  relation: BelongsToOneRelation
},
mother: {
  join: {
    from: 'student.motherId',
    to: 'mother.id'
  },
  modelClass: Mother,
  relation: BelongsToOneRelation
}

class entity has one relation:

student: {
  join: {
    from: 'student.classId',
    to: 'class.id'
  },
  modelClass: Student,
  relation: HasManyRelation
}

If I add two new named filters on the class model:

  • fatherName: filter classes that have students with fathers with a given name
qb.joinRelation('student.father').where('name', 'ilike', `%${value}%`)
  • motherName: filter classes classes that have students with mothers with a given name
qb.joinRelation('student.mother').where('name', 'ilike', `%${value}%`)

And if I try to use the two filters at the same time I receive the following error:

error: table name "student" specified more than once

I'm thinking on developing an util that will receive an instance of the QueryBuilder and a RelationExpression and check if the relation is already set. Set it if its a new relation and simply return the qb instance if its already defined.

Then the code of the filters would be something like this:

  • fatherName:
relationUtil(qb, 'student.father').where('name', 'ilike', `%${value}%`)
  • motherName:
relationUtil(qb, 'student.mother').where('name', 'ilike', `%${value}%`)

Is there any other way to work around this issue? If this is the only way, whats the best procedure to check if a relation is already defined on the QueryBuilder instance (checking paths like this: qb._operations[0].expression doesn't look like a great way).

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions