Skip to content

Inherited virtualAttributes are added to the database #1729

@kevhender

Description

@kevhender

Using a common Person model as a parent class, and multiple models that extend this class:

class Person extends Model {
  static get virtualAttributes() {
    return ['alphabeticalName', 'displayName', 'initials'];
  }

  alphabeticalName() {
    return [this.lastName, this.firstName].join(', ');
  }

  ...
}

class Customer extends Person {
  static get tableName() {
    return 'customer';
  }
}

When attempting to patch a Customer instance like so:

await Customer.query().patch(customer).findById(customer.id)

I am getting an error with alphabeticalName trying to be inserted:

column "alphabetical_name" of relation "customer" does not exist

I have found workarounds for this, but neither of them seems desirable. First, adding the property definition into the Customer class does work (without adding the virtualAttributes there). However, this defeats the purpose of having the Person class.

The other solution is to change the virtual attribute functions to be getters, like so:

class Person extends Model {
  static get virtualAttributes() {
    return ['alphabeticalName', 'displayName', 'initials'];
  }

  get alphabeticalName() {
    return [this.lastName, this.firstName].join(', ');
  }

  ...
}

This, however, yields this error:

TypeError: Cannot set property alphabeticalName of #<Person> which has only a getter

At this point, I can add a blank setter to get this to work properly:

class Person extends Model {
  static get virtualAttributes() {
    return ['alphabeticalName', 'displayName', 'initials'];
  }

  get alphabeticalName() {
    return [this.lastName, this.firstName].join(', ');
  }
  set alphabeticalName(_) {}

  ...
}

However, this seems like nothing more than a hack, one which is probably defeating the purpose of declaring virtualAttributes.

To me, this seems like a bug. I would think that adding these to the superclass would allow this to work properly. Is there something I am missing here?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions