Base class for all models.

This is used through patio.addModel, NOT directly.

Extends Static Properties
PropertyTypeDefault ValueDescription
MANY_TO_MANYproperty"manyToMany"

String for to signify an association as many to many.

MANY_TO_ONEproperty"manyToOne"

String for to signify an association as many to one.

ONE_TO_MANYproperty"oneToMany"

String for to signify an association as one to many.

ONE_TO_ONEproperty"oneToOne"

String for to signify an association as one to one.

camelize{Boolean} false

Set to true if this models column names should be use the "underscore" method when sending keys to the database and to "camelize" method on columns returned from the database. If set to false see patio.Model#underscore.

columnsString[]

A list of columns this models table contains.

datasetpatio.Dataset

A dataset to use to retrieve instances of this {@link patio.Model{ from the database. The dataset has the {@link patio.Dataset#rowCb} set to create instances of this model.

dbpatio.Database

The database all instances of this patio.Model use.

emitOnAssociationAddpropertytrue

Set to false to prevent an event from being emitted when an association is added to the model

emitOnColumnSetpropertytrue

Set to false to prevent the emitting of an event on the setting of a column value

emitOnLoadpropertytrue

Set to false to prevent the emitting of an event on load

emitOnRemovepropertytrue

Set to false to prevent the emitting on an event when a model is removed.

emitOnSavepropertytrue

Set to false to prevent the emitting on an event when a model is saved.

emitOnUpdatepropertytrue

Set to false to prevent the emitting on an event when a model is updated.

fetchTypepropertyfetch
identifierInputMethodpropertynull

See patio.Dataset#identifierInputMethod

identifierOutputMethodpropertynull

See patio.Dataset#identifierOutputMethod

isRestrictedPrimaryKeypropertyfalse

Set to false to allow the setting of primary keys.

patiofunction

A reference to the global patio.

primaryKeyfunction

The primaryKey column/s of this patio.Model

raiseOnTypecastErrorpropertytrue

Set to false to prevent errors thrown while type casting a value from being propogated.

reloadOnSavepropertytrue

Set to false to prevent the reload of a model after saving.

reloadOnUpdatepropertytrue

Set to false to prevent the reload of a model after updating.

restrictedColumnspropertynull

Columns that should be restriced when setting values through the patio.Model#set method.

schemaObject

The schema of this patio.Model's table. See patio.Database#schema for details on the schema object.

tablepropertynull

The table that this Model represents. READ ONLY

tableNameString

The name of the table all instances of the this patio.Model use.

typecastEmptyStringToNullpropertytrue

Set to false to prevent empty strings from being type casted to null

typecastOnAssignmentpropertytrue

Set to false to prevent properties from being type casted when manually set. See patio.Database#typecastValue

typecastOnLoadpropertytrue

Set to false to prevent properties from being type casted when loaded from the database. See patio.Database#typecastValue

underscore{Boolean} false

Set to true if this models column names should be use the "camelize" method when sending keys to the database and to "underscore" method on columns returned from the database. If set to false see patio.Model#underscore.

useTransactionspropertytrue

Set to false to prevent models from using transactions when saving, deleting, or updating. This applies to the model associations also.

Instance Properties
PropertyTypeDefault ValueDescription
__isChangedpropertyfalse

Signifies if the model has changed

__isNewpropertytrue

Whether or not this model is new

associationsfunction

List of associations on the patio.Model

columnsString[]

a list of columns this models table contains.

datasetpatio.Dataset

a dataset to use to retrieve models from the database. The dataset has the patio.Dataset#rowCb set to create instances of this model.

hasAssociationsfunction

Returns true if this patio.Model has associations.

isChangedBoolean

true if the model has been changed and not saved.

isNewBoolean

true if this model is new and does not exist in the database.

patiopationull

patio - read only

primaryKeyValue*

the value of this models primaryKey

schemaObject

the schema of this models table.

tableNameString

the table name of this models table.

typeStringnull

The database type such as mysql

Constructor

Defined model.js Source
  1. function (options,fromDb){
  2. if (this.synced) {
  3. this.__emitter = new EventEmitter();
  4. this._super(arguments);
  5. this.patio = patio || require("./index");
  6. fromDb = isBoolean(fromDb) ? fromDb : false;
  7. this.__changed = {};
  8. this.__values = {};
  9. if (fromDb) {
  10. this._hook("pre", "load");
  11. this.__isNew = false;
  12. this.__setFromDb(options, true);
  13. if (this._static.emitOnLoad) {
  14. this.emit("load", this);
  15. this._static.emit("load", this);
  16. }
  17. } else {
  18. this.__isNew = true;
  19. this.__set(options);
  20. }
  21. } else {
  22. throw new ModelError("Model " + this.tableName + " has not been synced");
  23. }
  24. }

associate Static Function Public


Defined plugins/association.js

Associates a related model with the current model. The following types are supported:

Arguments Source
  1. function (type,name,options,filter){
  2. if (comb.isFunction(options)) {
  3. filter = options;
  4. options = {};
  5. }
  6. this.__associations = this.__associations || {manyToMany: {}, oneToMany: {}, manyToOne: {}, oneToOne: {}};
  7. var assoc = new associations[type](comb.merge({model: name}, options), this.patio, filter);
  8. assoc.inject(this, name);
  9. this.__associations[type][name] = assoc;
  10. this.emit("associate", type, this);
  11. return this;
  12. }

create Static Function Public


Defined model.js

Create a new model initialized with the specified values.

Arguments Returns Source
  1. function (values){
  2. //load an object from an object
  3. var Self = this;
  4. return new Self(values, false);
  5. }

find Static Function Public


Defined plugins/query.js

Finds a single model according to the supplied filter. See patio.Dataset#filter for filter options.

Arguments Source
  1. function (id){
  2. return this.filter.apply(this, arguments).first();
  3. }

findById Static Function Public


Defined plugins/query.js

Retrieves a record by the primaryKey/s of a table.

Example
  1. var User = patio.getModel("user");
  2.  
  3. User.findById(1).chain(function(userOne){
  4.  
  5. });
  6.  
  7. //assume the primary key is a compostie of first_name and last_name
  8. User.findById(["greg", "yukon"]).chain(function(userOne){
  9.  
  10. });
Arguments Returns Source
  1. function (id){
  2. var pk = this.primaryKey;
  3. pk = pk.length === 1 ? pk[0] : pk;
  4. var q = {};
  5. if (isArray(id) && isArray(pk)) {
  6. if (id.length === pk.length) {
  7. pk.forEach(function (k, i) {
  8. q[k] = id[i];
  9. });
  10. } else {
  11. throw new ModelError("findById : ids length does not equal the primaryKeys length.");
  12. }
  13. } else {
  14. q[pk] = id;
  15. }
  16. return this.filter(q).one();
  17. }

findOrCreate Static Function Public


Defined plugins/query.js

Finds a single model according to the supplied filter. See patio.Dataset#filter for filter options. If the model does not exist then a new one is created as passed back.

Arguments Source
  1. function (q){
  2. var self = this;
  3. return this.find(q).chain(function (res) {
  4. return res || self.create(q);
  5. });
  6. }

inherits Static Function Public


Defined model.js

Stub for plugins to notified of model inheritance

Arguments Source
  1. function (model){
  2. }

manyToMany Static Function Public


Defined plugins/association.js

Creates a MANY_TO_MANY relationship between models. See patio.plugins.AssociationPlugin.associate for options.

Example
  1. patio.addModel("class", {
  2. static:{
  3. init:function(){
  4. this._super("arguments");
  5. this.manyToMany("students", {fetchType:this.fetchType.EAGER, order : [sql.firstName.desc(), sql.lastName.desc()]});
  6. }
  7. }
  8. });
  9. patio.addModel("student", {
  10. instance:{
  11. enroll:function(clas){
  12. if (comb.isArray(clas)) {
  13. return this.addClasses(clas);
  14. } else {
  15. return this.addClass(clas);
  16. }
  17. }
  18. },
  19. static:{
  20. init:function(){
  21. this._super("arguments");
  22. this.manyToMany("classes", {fetchType:this.fetchType.EAGER, order : sql.name.desc()});
  23. }
  24. }
  25. });
Arguments Source
  1. function (name,options,filter){
  2. return this.associate(this.MANY_TO_MANY, name, options, filter);
  3. }

manyToOne Static Function Public


Defined plugins/association.js

Creates a MANY_TO_ONE association. See patio.plugins.AssociationPlugin.oneToMany. See patio.plugins.AssociationPlugin.associate

Arguments Source
  1. function (name,options,filter){
  2. return this.associate(this.MANY_TO_ONE, name, options, filter);
  3. }

oneToMany Static Function Public


Defined plugins/association.js

Creates a ONE_TO_MANY association. See patio.plugins.AssociationPlugin.associate for options.

Example
  1. //define the BiologicalFather model
  2. patio.addModel("biologicalFather", {
  3. static:{
  4. init:function () {
  5. this._super("arguments");
  6. this.oneToMany("children");
  7. }
  8. }
  9. });
  10.  
  11.  
  12. //define Child model
  13. patio.addModel("child", {
  14. static:{
  15. init:function () {
  16. this._super("arguments");
  17. this.manyToOne("biologicalFather");
  18. }
  19. }
  20. });
Arguments Source
  1. function (name,options,filter){
  2. return this.associate(this.ONE_TO_MANY, name, options, filter);
  3. }

oneToOne Static Function Public


Defined plugins/association.js

Creates a ONE_TO_ONE relationship between models. See patio.plugins.AssociationPlugin.associate for options.

Example
  1. patio.addModel("state", {
  2. static:{
  3. init:function () {
  4. this._super("arguments");
  5. this.oneToOne("capital");
  6. }
  7. }
  8. });
  9.  
  10. patio.addModel("capital", {
  11. static:{
  12. init:function () {
  13. this._super("arguments");
  14. this.manyToOne("state");
  15. }
  16. }
  17. });
Arguments Source
  1. function (name,options,filter){
  2. return this.associate(this.ONE_TO_ONE, name, options, filter);
  3. }

remove Static Function Public


Defined plugins/query.js

Remove(delete) models. This can be used to do a mass delete of models.

Example
  1. var User = patio.getModel("user");
  2.  
  3. //remove all users
  4. User.remove();
  5.  
  6. //remove all users who's names start with a.
  7. User.remove({name : /A%/i});
  8.  
  9. //remove all users who's names start with a, without a transaction.
  10. User.remove({name : /A%/i}, {transaction : false});
Arguments Returns Source
  1. function (q,options){
  2. options = options || {};
  3. var loadEach = isBoolean(options.load) ? options.load : true;
  4. //first find all records so we call alert the middleware for each model
  5. var ds = this.dataset.filter(q);
  6. return this._checkTransaction(options, function () {
  7. if (loadEach) {
  8. return ds.map(function (r) {
  9. //todo this sucks find a better way!
  10. return r.remove(options);
  11. });
  12. } else {
  13. return ds.remove();
  14. }
  15. });
  16. }

removeById Static Function Public


Defined plugins/query.js

Similar to remove but takes an id or an array for a composite key.

Example
  1. User.removeById(1);
Arguments Returns Source
  1. function (id,options){
  2. var self = this;
  3. return this._checkTransaction(options, function () {
  4. return self.findById(id).chain(function (model) {
  5. return model ? model.remove(options) : null;
  6. });
  7. });
  8. }

save Static Function Public


Defined plugins/query.js

Save either a new model or list of models to the database.

Example
  1. var Student = patio.getModel("student");
  2. Student.save([
  3. {
  4. firstName:"Bob",
  5. lastName:"Yukon",
  6. gpa:3.689,
  7. classYear:"Senior"
  8. },
  9. {
  10. firstName:"Greg",
  11. lastName:"Horn",
  12. gpa:3.689,
  13. classYear:"Sohpmore"
  14. },
  15. {
  16. firstName:"Sara",
  17. lastName:"Malloc",
  18. gpa:4.0,
  19. classYear:"Junior"
  20. },
  21. {
  22. firstName:"John",
  23. lastName:"Favre",
  24. gpa:2.867,
  25. classYear:"Junior"
  26. },
  27. {
  28. firstName:"Kim",
  29. lastName:"Bim",
  30. gpa:2.24,
  31. classYear:"Senior"
  32. },
  33. {
  34. firstName:"Alex",
  35. lastName:"Young",
  36. gpa:1.9,
  37. classYear:"Freshman"
  38. }
  39. ]).chain(function(users){
  40. //work with the users
  41. });
  42.  
  43. Save a single record
  44. MyModel.save(m1);
Arguments Returns Source
  1. function (items,options){
  2. options = options || {};
  3. var isArr = isArray(items), Self = this;
  4. return this._checkTransaction(options, function () {
  5. return asyncArray(items)
  6. .map(function (o) {
  7. if (!isInstanceOf(o, Self)) {
  8. o = new Self(o);
  9. }
  10. return o.save(null, options);
  11. })
  12. .chain(function (res) {
  13. return isArr ? res : res[0];
  14. });
  15. });
  16. }

update Static Function Public


Defined plugins/query.js

Update multiple rows with a set of values.

Example
  1. var User = patio.getModel("user");
  2.  
  3. //BEGIN
  4. //UPDATE `user` SET `password` = NULL WHERE (`last_accessed` <= '2011-01-27')
  5. //COMMIT
  6. User.update({password : null}, function(){
  7. return this.lastAccessed.lte(comb.date.add(new Date(), "year", -1));
  8. });
  9. //same as
  10. User.update({password : null}, {lastAccess : {lte : comb.date.add(new Date(), "year", -1)}});
  11.  
  12. //UPDATE `user` SET `password` = NULL WHERE (`last_accessed` <= '2011-01-27')
  13. User.update({password : null}, function(){
  14. return this.lastAccessed.lte(comb.date.add(new Date(), "year", -1));
  15. }, {transaction : false});
Arguments Returns Source
  1. function (vals,/*?object*/query,options){
  2. options = options || {};
  3. var dataset = this.dataset;
  4. return this._checkTransaction(options, function () {
  5. if (!isUndefined(query)) {
  6. dataset = dataset.filter(query);
  7. }
  8. return dataset.update(vals);
  9. });
  10. }

useTransaction Static Function Private


Defined model.js

Arguments Source
  1. function (opts){
  2. opts = opts || {};
  3. return isBoolean(opts.transaction) ? opts.transaction === true : this.useTransactions === true;
  4. }

__reload Function Private


Defined plugins/query.js

Forces the reload of the data for a particular model instance. The Promise returned is resolved with the model.

Example
  1. myModel.reload().chain(function(model){
  2. //model === myModel
  3. });
Returns Source
  1. function (){
  2. if (!this.__isNew) {
  3. var self = this;
  4. return this.dataset.naked().filter(this._getPrimaryKeyQuery()).one().chain(function (values) {
  5. self.__setFromDb(values, true);
  6. return self;
  7. });
  8. } else {
  9. return when(this);
  10. }
  11. }

_saveReload Function Private


Defined plugins/query.js

Arguments Source
  1. function (options){
  2. options || (options = {});
  3. var reload = isBoolean(options.reload) ? options.reload : this._static.reloadOnSave;
  4. return reload ? this.__reload() : when(this);
  5. }

_updateReload Function Private


Defined plugins/query.js

Arguments Source
  1. function (options){
  2. options = options || {};
  3. options || (options = {});
  4. var reload = isBoolean(options.reload) ? options.reload : this._static.reloadOnUpdate;
  5. return reload ? this.__reload() : when(this);
  6. }

remove Function Public


Defined plugins/query.js

This method removes the instance of the model. If the model patio.Model#isNew then the promise is resolved with a 0 indicating no rows were affected. Otherwise the model is removed, primary keys are cleared and the model's isNew flag is set to true.

Example
  1. myModel.remove().chain(function(){
  2. //model is deleted
  3. assert.isTrue(myModel.isNew);
  4. });
  5.  
  6. //dont use a transaction to remove this model
  7. myModel.remove({transaction : false}).chain(function(){
  8. //model is deleted
  9. assert.isTrue(myModel.isNew);
  10. });
Arguments Returns Source
  1. function (options){
  2. if (this.synced) {
  3. if (!this.__isNew) {
  4. var self = this;
  5. return this._checkTransaction(options, function () {
  6. return self.__callHooks("remove", [options], function () {
  7. return self._remove(options);
  8. })
  9. .chain(function () {
  10. self._clearPrimaryKeys();
  11. self.__isNew = true;
  12. if (self._static.emitOnRemove) {
  13. self.emit("remove", this);
  14. self._static.emit("remove", this);
  15. }
  16. })
  17. .chain(function () {
  18. return self;
  19. });
  20. });
  21. } else {
  22. return when(0);
  23. }
  24. } else {
  25. throw new ModelError("Model " + this.tableName + " has not been synced");
  26. }
  27. }

save Function Public


Defined plugins/query.js

Saves a model. This action checks if the model is new and values have changed. If the model is not new then the patio.Model#update action is called.

When saving a model you can pass values you want set as the first argument.

  1.  
  2.  
  3. someModel.save({
  4. myVal1 : "newValue1",
  5. myVal2 : "newValue2",
  6. myVal3 : "newValue3"
  7. }).chain(function(){
  8. //do something
  9. }, errorHandler);
  10.  
  11.  

Or you can set values on the model directly

  1.  
  2.  
  3. someModel.myVal1 = "newValue1";
  4. someModel.myVal2 = "newValue2";
  5. someModel.myVal3 = "newValue3";
  6.  
  7. //update model with current values
  8. someModel.save().chain(function(){
  9. //do something
  10. });
  11.  
  12.  

Save also accepts an options object as the second argument allowing the overriding of default behavior.

To override useTransactions you can set the transaction option.

  1.  
  2. someModel.save(null, {transaction : false});
  3.  

You can also override the reloadOnSave property by setting the reload option.

  1.  
  2. someModel.save(null, {reload : false});
  3.  

Arguments Returns Source
  1. function (vals,options){
  2. if (this.synced) {
  3. if (this.__isNew) {
  4. var self = this;
  5. return this._checkTransaction(options, function () {
  6. if (isHash(vals)) {
  7. self.__set(vals);
  8. }
  9. return self.__callHooks("save", [options], function () {
  10. return self._save(options);
  11. })
  12. .chain(function () {
  13. return self._saveReload(options);
  14. })
  15. .chain(function () {
  16. if (self._static.emitOnSave) {
  17. self.emit("save", self);
  18. self._static.emit("save", self);
  19. }
  20. })
  21. .chain(function () {
  22. return self;
  23. });
  24. });
  25. } else {
  26. return this.update(vals, options);
  27. }
  28. } else {
  29. throw new ModelError("Model " + this.tableName + " has not been synced");
  30. }
  31. }

setValues Function Public


Defined model.js

Set multiple values at once. Useful if you have a hash of properties that you want to set.

NOTE: This method will use the static restrictedColumns property of the model.

Example
  1. myModel.setValues({firstName : "Bob", lastName : "yukon"});
  2.  
  3. //this will throw an error by default, assuming id is a pk.
  4. myModel.setValues({id : 1, firstName : "Bob", lastName : "yukon"});
Arguments Returns Source
  1. function (values){
  2. this.__set(values, false);
  3. return this;
  4. }

toJSON Function Public


Defined model.js

Convert this model to JSON, containing column, value pairs.

Returns Source
  1. function (){
  2. return this.toObject();
  3. }

toObject Function Public


Defined model.js

Convert this model to an object, containing column, value pairs.

Returns Source
  1. function (){
  2. return this._toObject(false);
  3. }

toString Function Public


Defined model.js

Convert this model to a string, containing column, value pairs.

Returns Source
  1. function (){
  2. return JSON.stringify(this.toObject(), null, 4);
  3. }

update Function Public


Defined plugins/query.js

Updates a model. This action checks if the model is not new and values have changed. If the model is new then the patio.Model#save action is called.

When updating a model you can pass values you want set as the first argument.

  1.  
  2.  
  3. someModel.update({
  4. myVal1 : "newValue1",
  5. myVal2 : "newValue2",
  6. myVal3 : "newValue3"
  7. }).chain(function(){
  8. //do something
  9. }, errorHandler);
  10.  
  11.  

Or you can set values on the model directly

  1.  
  2.  
  3. someModel.myVal1 = "newValue1";
  4. someModel.myVal2 = "newValue2";
  5. someModel.myVal3 = "newValue3";
  6.  
  7. //update model with current values
  8. someModel.update().chain(function(){
  9. //do something
  10. });
  11.  
  12.  

Update also accepts an options object as the second argument allowing the overriding of default behavior.

To override useTransactions you can set the transaction option.

  1.  
  2. someModel.update(null, {transaction : false});
  3.  

You can also override the reloadOnUpdate property by setting the reload option.

  1.  
  2. someModel.update(null, {reload : false});
  3.  

Arguments Returns Source
  1. function (vals,options){
  2. if (this.synced) {
  3. if (!this.__isNew) {
  4. var self = this;
  5. return this._checkTransaction(options, function () {
  6. if (isHash(vals)) {
  7. self.__set(vals);
  8. }
  9. var saveChange = !isEmpty(self.__changed);
  10. return self.__callHooks("update", [options], function () {
  11. return saveChange ? self._update(options) : null;
  12. })
  13. .chain(function () {
  14. return self._updateReload(options);
  15. })
  16. .chain(function () {
  17. if (self._static.emitOnUpdate) {
  18. self.emit("update", self);
  19. self._static.emit("update", self);
  20. }
  21. })
  22. .chain(function () {
  23. return self;
  24. });
  25. });
  26. } else if (this.__isNew && this.__isChanged) {
  27. return this.save(vals, options);
  28. } else {
  29. return when(this);
  30. }
  31. } else {
  32. throw new ModelError("Model " + this.tableName + " has not been synced");
  33. }
  34. }

valueOf Function Public


Defined model.js

Convert this model to a string, containing column, value pairs.

Returns Source
  1. function (){
  2. return this.toObject();
  3. }

Documentation generated using coddoc.