Skip to content

relatedQuery will not provide an alias for a self-referring relation #859

@besuhoff

Description

@besuhoff

First of all I'd like to express my greatest appreciation for the work you do as objection.js is in my opinion the best Node ORM and is maintained with the highest quality and the shortest reaction time one could expect. Thank you very much!

Now, the issue I'm trying to deal with (might be a user error):

class Category extends Model {
  static get tableName() {
    return 'category';
  }

  static get relationMappings() {
    return {
      parent: {
        relation: Model.BelongsToOneRelation,
        modelClass: Category,
        join: {
          from: 'category.parentId',
          to: 'category.id',
        },
      },
      children: {
        relation: Model.HasManyRelation,
        modelClass: Category,
        join: {
          from: 'category.id',
          to: 'category.parentId',
        },
      },
    };
  }
}

Category.query
  .select('category.*', Category.relatedQuery('children').select(Category.raw('count(*) = 0')).as('isLinked'));

Here I'm trying to select the Boolean of if a category has children into a specific field.

That would compile to the following:

  sql: 'select `category`.*, (select count(*) = 0 from `category` where `category`.`parentId` = `category`.`id`) as `isLinked` from `category`' }

— which would not work because related table has the same name (obviously), and that would override the outer query. Shouldn't it be considered on a relation that if the table names in from and to are equal, then we should add a pseudo name to it?

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions