I am designing a custom Model structure for my NodeJS project. I have created a base class named Model which is inherited by other model classes. The base model class will have a set of properties that needs to be accessed by the methods. The properties will get overwritten by child classes as shown in the examples below(by User model).
There is a table property which I need to access from both static as well as non-static methods as such:
Case 1: Base model class has non-static property table.
class Model {
protected table = '';
public static find(id: number) {
// I want to have table name in here but cant.
}
public save() {
// I am able to get table name in here `this`.
}
}
class User extends Model {
protected table = 'users'; // overwriting parent's table property
// list of other non static properties in here
constructor(user: UserSchema) {
// assign non static properties from here
}
}
Case 2: Base model class has static property table.
class Model {
protected static table = '';
public static find(id: number) {
// I am able to get table name in here using `this`.
}
public save() {
// I want to have table name in here but cant.
}
}
class User extends Model {
protected static table = 'users'; // overwriting parent's table property
// list of other non static properties in here
constructor(user: UserSchema) {
// assign non static properties from here
}
}
I tried changing the static and non-static nature of table property but whenever I switch, there occurs two scenarios.
- Either static method can only access static property.
- Or non-static method can only access non-static property.
I could access static property using class name(e.g.
Model.table) but it will result base model's empty value("") and I need the User's overloaded table value('users') to work.
I want to have control over both the scenarios where I could get the properties interchangibly(accessing static property from non static method as well as static property from non static method). How can I acheive this behaviour? Any suggestion is appreciated.
Model.tablein case 2save. But you cannot refer to an instance property in a static context without an instance at-hand.usersset from User model is not received in the base class. It returns empty string(which is the default value of the property). I want to have the value accessed in here as well. Much like the laravel framwork where the table name set from child classes gets available to the base eloquent models.