Model
Models wrap your database, and allow you to define relationships.
Class vs. instance methods
The methods documented below apply to instances of models, but you'll typically use the Schema
to access the model class, which can be used to find or create instances.
You can find the Class methods documented under the Schema
API docs.
Accessing properties and relationships
You can access properites (fields) and relationships directly off of models.
user.name; // 'Sam'
user.team; // Team model
user.teamId; // Team id (foreign key)
Mirage Models are schemaless in their attributes, but their relationship schema is known.
For example,
let user = schema.users.create();
user.attrs // { }
user.name // undefined
let user = schema.users.create({ name: 'Sam' });
user.attrs // { name: 'Sam' }
user.name // 'Sam'
However, if a user
has a posts
relationships defined,
let user = schema.users.create();
user.posts // returns an empty Posts Collection
Properties
associations: Object
Returns a hash of this model's associations.
let server = new Server({
models: {
user: Model,
post: Model.extend({
user: belongsTo(),
comments: hasMany()
}),
comment: Model
},
seeds(server) {
let peter = server.create("user", { name: "Peter" });
server.create("post", { user: peter });
}
});
let post = server.schema.posts.find(1)
post.associations
// {
// user: BelongsToAssociation,
// comments: HasManyAssociation
// }
Check out the docs on the Association class to see what fields are available for each association.
attrs: any
Returns the attributes of your model.
let post = schema.blogPosts.find(1);
post.attrs; // {id: 1, title: 'Lorem Ipsum', publishedAt: '2012-01-01 10:00:00'}
Note that you can also access individual attributes directly off a model, e.g. post.title
.
Methods
destroy(): any
Destroys the db record.
let post = blogPosts.find(1);
post.destroy(); // removed from the db
isNew(): Boolean
Boolean, true if the model has not been persisted yet to the db.
let post = blogPosts.new({title: 'Lorem ipsum'});
post.isNew(); // true
post.id; // null
post.save(); // true
post.isNew(); // false
post.id; // 1
isSaved(): Boolean
Boolean, opposite of isNew
reload(): any
Reload a model's data from the database.
let post = blogPosts.find(1);
post.attrs; // {id: 1, title: 'Lorem ipsum'}
post.title = 'Hipster ipsum';
post.title; // 'Hipster ipsum';
post.reload(); // true
post.title; // 'Lorem ipsum'
save(): any
Create or saves the model.
let post = blogPosts.new({ title: 'Lorem ipsum' });
post.id; // null
post.save();
post.id; // 1
post.title = 'Hipster ipsum'; // db has not been updated
post.save(); // ...now the db is updated
toString(): String
Simple string representation of the model and id.
let post = blogPosts.find(1);
post.toString(); // "model:blogPost:1"
update(key: String, val: String): any
Updates the record in the db.
let post = blogPosts.find(1);
post.update('title', 'Hipster ipsum'); // the db was updated
post.update({
title: 'Lorem ipsum',
created_at: 'before it was cool'
});