Skip to content

Unnecessary join: foreign key same as property name #249

@emrosenf

Description

@emrosenf

Describe the bug

I am migrating a project where the foreign key in the database is not suffixed with Id. For example, the database table looks like this:

CREATE TABLE "Profile" (
  "id" TEXT NOT NULL   ,
  "user" TEXT    REFERENCES "User"(id) ON DELETE SET NULL,
  PRIMARY KEY ("id")
)

The problem is that when you query this class like so:

em.find(Profile, { user: { $in: [userId] }, })

The code below in ObjectCriteriaNode will trigger. It will see that user is a non-scalar field and join in the User table, even though I'm really just trying to query on an indexed foreign key that happens to also be called user in the database.

export class ObjectCriteriaNode extends CriteriaNode {

  static create(metadata: MetadataStorage, entityName: string, payload: Dictionary, parent?: CriteriaNode, key?: string): ObjectCriteriaNode {
    const node = new ObjectCriteriaNode(metadata, entityName, parent, key);
    const meta = metadata.get(entityName, false, false);
    node.payload = Object.keys(payload).reduce((o, item) => {
      // prop is defined because "user" is a defined relationship
      // as well as the name of the database field that holds the foreign key
      const prop = meta && meta.properties[item];
      const childEntity = prop && prop.reference !== ReferenceType.SCALAR ? prop.type : entityName;
      o[item] = CriteriaNode.create(metadata, childEntity, payload[item], node, item);

      return o;
    }, {});

    return node;
  }

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions