Extending models using JSON
When you create a model with the Model generator, you choose a base model, that is, the model that your model will "extend" and from which it will inherit methods and properties. The tool will set the base property in the model definition JSON file accordingly. For example, for a model that extends PersistedModel:
{ "name": "Order", "base": "PersistedModel", ...
To change the base model, simply edit the JSON file and change the base
property.
See Customizing models for general information on how to create a model that extends (or "inherits from") another model.
Extending a model in JavaScript
You can also extend models using JavaScript file in the model JavaScript file, /common/models/modelName.js
(where modelName
is the name of the model); for example:
var properties = { firstName: {type: String, required: true} }; var options = { relations: { accessTokens: { model: accessToken, type: hasMany, foreignKey: userId }, account: { model: account, type: belongsTo }, transactions: { model: transaction, type: hasMany } }, acls: [ { permission: ALLOW, principalType: ROLE, principalId: $everyone, property: myMethod } ] }; var user = loopback.Model.extend('user', properties, options);
Mixing in model definitions
You may want to create models that share a common set of properties and logic. LoopBack enables you to "mix-in" one or more other models into a single model; for example:
var TimeStamp = modelBuilder.define('TimeStamp', {created: Date, modified: Date}); var Group = modelBuilder.define('Group', {groups: [String]}); User.mixin(Group, TimeStamp);