Options
All
  • Public
  • Public/Protected
  • All
Menu

Class Model

Model is the base class for classes representing relational data in terms of objects.

Model extends from your ORM's Model native model class(eg:- for Sequelize, sequelize.Model) and hence have all the features and behaviors included in the ORM's model class.

As an example, say that the Customer Model class is associated with the customer table. This would mean that the class's name attribute is automatically mapped to the name column in customer table. Thanks to Model, assuming the variable customer is an object of type Customer, to get the value of the name column for the table row, you can use the expression customer.name. In this example, Model is providing an object-oriented interface for accessing data stored in the database. But Model provides much more functionality than this.

All the models used for Pwoli components should be extended from Model

To declare a Model class you need to extend Model

class Customer extends Model
{
static associate() { // your model relations
Customer.hasMany(Order, { as: 'orders', foreignKey: 'customerId' });
...
}
...
// your additional implementations here..
...
}

Important Note: If your ORM is Sequelize, you should perform additional steps like defining the model attributes and options for initializing each model like below:

const attributes = {
id: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: null,
primaryKey: true,
autoIncrement: true,
email: {
type: DataTypes.STRING(255),
allowNull: false,
defaultValue: null,
primaryKey: false,
autoIncrement: false,
comment: null,
field: 'email',
validate: {
isEmail: { msg: "Please enter a valid Email" },
},
...
},
};
const options = {
tableName: 'Customer',
comment: '',
sequelize,
hooks: {},
};
Customer.init(eventAttributes, eventOptions);
Customer.associate(); //for associating relations like `hasOne`, `hasMany` etc.

Class instances are obtained in one of two ways:

  • Using the new operator to create a new, empty object
  • Using a method to fetch an existing record (or records) from the database

Below is an example showing some typical usage of Model:

let user = new User();
user.name = 'Mahesh';
await user.save(); // a new row is inserted into user table

// the following will retrieve the user 'Mahesh' from the database
let user = await User.findOne({where: {name: 'Mahesh'});

// this will get related records from orders table when relation is defined. Please note that you need to `include` the required relations like below:
let user = await User.findOne({where: {name: 'Mahesh'}, include: [{ model: Order, as: 'orders' }]);
let orders = user.orders;

If your ORM is Sequelize, please refer https://sequelize.org/master/manual/model-basics.html

author

Mahesh S Warrier https://github.com/codespede

Hierarchy

  • ORMModel
    • Model

Index

Constructors

  • new Model(config?: {}): Model
  • Parameters

    • config: {} = {}
      • [key: string]: any

    Returns Model

Properties

_errors: {} = {}

Validation errors (attribute name => array of errors)

Type declaration

  • [key: string]: any
getAttributeHints: () => {} = ...

Type declaration

    • (): {}
    • Attribute hints are mainly used for display purpose. For example, given an attribute isPublic, we can declare a hint Whether the post should be visible for not logged in users, which provides user-friendly description of the attribute meaning and can be displayed to end users. Eg:-

      export class Event extends Model {
      getAttributeHints() {
      return {
      firstName: 'First Name',
      ...
      }
      };

      Returns {}

      • [key: string]: string
init: any

Methods

  • activeAttributes(): string[]
  • Returns the attribute names that are subject to validation in the current scenario.

    Returns string[]

    active attribute names

  • clearErrors(attribute?: string): void
  • Removes errors for all attributes or a single attribute.

    Parameters

    • attribute: string = null

      attribute name. Use null to remove errors for all attributes.

    Returns void

  • getActiveValidators(attribute?: string): {}
  • Returns the validators applicable.

    Parameters

    • attribute: string = null

    Returns {}

    the validators applicable.

    • [key: string]: any
  • getAttributeHint(attribute: any): string
  • Returns the text hint for the specified attribute.

    see

    [[attributeHints]]

    since

    2.0.4

    Parameters

    • attribute: any

    Returns string

    string the attribute hint

  • getAttributeLabel(attribute: string): string
  • Returns the text label for the specified attribute. If the attribute looks like relatedModel.attribute, then the attribute will be received from the related model.

    see

    [[attributeLabels]]

    Parameters

    • attribute: string

      the attribute name

    Returns string

    the attribute label

  • getAttributeLabels(): {}
  • Attribute labels are mainly used for display purpose. For example, given an attribute firstName, we can declare a label First Name which is more user-friendly and can be displayed to end users. Eg:-

    export class Event extends Model {
    getAttributeLabels() {
    return {
    firstName: 'First Name',
    ...
    }
    };

    Returns {}

    • [key: string]: string
  • getFirstError(attribute: string): string
  • Returns the first error of the specified attribute.

    Parameters

    • attribute: string

    Returns string

    the error message. Null is returned if no error.

  • getFormName(): string
  • Returns the form name that this model class should use.

    The form name is mainly used by ActiveForm to determine how to name the input fields for the attributes in a model. If the form name is "A" and an attribute name is "b", then the corresponding input name would be "A[b]". If the form name is an empty string, then the input name would be "b".

    The purpose of the above naming schema is that for forms which contain multiple different models, the attributes of each model are grouped in sub-arrays of the POST-data and it is easier to differentiate between them.

    By default, this method returns the model class name as the form name. You may override it when the model is used in different forms.

    see

    load

    Returns string

    the form name of this model class.

  • hasErrors(attribute?: string): boolean
  • Returns a value indicating whether there is any validation error.

    Parameters

    • attribute: string = null

      name. Use null to check all attributes.

    Returns boolean

    whether there is any error.

  • isAttributeRequired(attribute: string): boolean
  • Returns a value indicating whether the attribute is required.

    Parameters

    • attribute: string

    Returns boolean

    whether the attribute is required

  • load(data: {}, formName?: string): boolean
  • Populates the model with input data.

    This method provides a convenient shortcut for:

    if (request.body['FormName]) {
    model.setAttributeValues(request.body['FormName]);
    if (model.save()) {
    // handle success
    }
    }

    which, with load() can be written as:

    if (model.load(request.body) && model.save()) {
    // handle success
    }

    load() gets the 'FormName' from the model's getFormName method (which you may override), unless the $formName parameter is given. If the form name is empty, load() populates the model with the whole of data, instead of data['FormName'].

    Note, that the data being populated is subject to the safety check by setAttributeValues.

    Parameters

    • data: {}
      • [key: string]: any
    • formName: string = null

    Returns boolean

    whether load() found the expected form in data.

  • Searches the DB with the params provided.

    Parameters

    • params: {}

      The search params in a key-value format like: { status:1, title: 'My Titile', ...}

      • [key: string]: string

    Returns ActiveDataProvider

    the ActiveDataProvider which can provide the relevant results.

  • setAttributeValues(values: {}): Model
  • Sets the attribute values in a massive way.

    Parameters

    • values: {}

      attribute values (name => value) to be assigned to the model.

      • [key: string]: any

    Returns Model

  • verify(attributeNames?: string[], clearErrors?: boolean): Promise<boolean>
  • Performs the data validation.

    This method executes the validation rules. Errors found during the validation can be retrieved via Model._errors and [[getFirstError()]].

    Parameters

    • attributeNames: string[] = null

      attribute name or list of attribute names that should be validated. If this parameter is empty, it means any attribute listed in the applicable validation rules should be validated.

    • clearErrors: boolean = true

      whether to call clearErrors before performing validation

    Returns Promise<boolean>

    whether the validation is successful without any error.

  • primaryKey(): string
  • Returns the primary key for this Model class. By default, this returns id

    Returns string

Generated using TypeDoc