• CakePHP
  • Downloads
    • Releases
    • Pear channel
  • Documentation
    • API
      • 2.3 |
      • 2.2 |
      • 1.3 |
      • 1.2 |
      • 1.1
    • Book
      • 2.x |
      • 1.3 |
      • 1.2 |
      • 1.1
  • Community
    • Issues
    • Bakery
    • Plugins & packages
    • Contributors
    • Google Groups
    • Logo
    • Q & A
    • TV (Screencasts)
  • Services
    • Certification
    • Consultation
    • Support
    • Training
API
Version 2.3
  • 1.2
  • 1.3
  • 2.0
  • 2.1
  • 2.2
  • 2.3
  • 2.4
  • Overview
  • Tree
  • Deprecated

Packages

  • app
    • Config
      • Schema
    • Console
      • Command
    • Controller
    • Model
    • View
      • Helper
  • Cake
    • Cache
      • Engine
    • Configure
    • Console
      • Command
        • Task
    • Controller
      • Component
        • Acl
        • Auth
    • Core
    • Error
    • Event
    • I18n
    • Log
      • Engine
    • Model
      • Behavior
      • Datasource
        • Database
        • Session
      • Validator
    • Network
      • Email
      • Http
    • Routing
      • Filter
      • Route
    • TestSuite
      • Coverage
      • Fixture
      • Reporter
    • Utility
    • View
      • Helper
  • PHP

Classes

  • AclNode
  • Aco
  • AcoAction
  • Aro
  • BehaviorCollection
  • CakeSchema
  • ConnectionManager
  • DbAclSchema
  • I18nModel
  • Model
  • ModelBehavior
  • ModelValidator
  • Permission
  • SessionsSchema
  • Package
  • Class

Class Model

Object-relational mapper.

DBO-backed object data model. Automatically selects a database table name based on a pluralized lowercase object class name (i.e. class 'User' => table 'users'; class 'Man' => table 'men') The table is required to have at least 'id auto_increment' primary key.

Object
Extended by Model implements CakeEventListener
Direct known subclasses
AclNode, AppModel, CakeTestModel
Indirect known subclasses
Aco, AcoAction, Aro, I18nModel, Permission
Package: Cake\Model
Copyright: Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
License: License (http://www.opensource.org/licenses/mit-license.php)
Link: http://book.cakephp.org/2.0/en/models.html
Located at Cake/Model/Model.php

Method summary

public __call ( string $method , array $params )

Handles custom method calls, like findBy<field> for DB models, and custom RPC calls for remote data sources.

public __construct ( integer|string|array $id = false , string $table = null , string $ds = null )

Constructor. Binds the model's database table to the object.

public __get ( string $name )

Returns the value of the requested variable if it can be set by __isset()

public __isset ( string $name )

Handles the lazy loading of model associations by looking in the association arrays for the requested variable

protected _addToWhiteList ( string $key , array $options )

Helper method for saveAll() and friends, to add foreign key to fieldlist

protected _clearCache ( string $type = null )

Clears cache for this model.

protected _collectForeignKeys ( string $type = 'belongsTo' )

Collects foreign keys from associations.

protected _constructLinkedModel ( string $assoc , string $className = null , string $plugin = null )

Protected helper method to create associated models of a given class.

protected _createLinks ( )

Create a set of associations.

protected _deleteDependent ( string $id , boolean $cascade )

Cascades model deletes through associated hasMany and hasOne child records.

protected _deleteLinks ( string $id )

Cascades model deletes through HABTM join keys.

protected _filterResults ( array $results , boolean $primary = true )

Passes query results through model and behavior afterFilter() methods.

protected _findCount ( string $state , array $query , array $results = array() )

Handles the before/after filter logic for find('count') operations. Only called by Model::find().

protected _findFirst ( string $state , array $query , array $results = array() )

Handles the before/after filter logic for find('first') operations. Only called by Model::find().

protected _findList ( string $state , array $query , array $results = array() )

Handles the before/after filter logic for find('list') operations. Only called by Model::find().

protected _findNeighbors ( string $state , array $query , array $results = array() )

Detects the previous field's value, then uses logic to find the 'wrapping' rows and return them.

protected _findThreaded ( string $state , mixed $query , array $results = array() )

In the event of ambiguous results returned (multiple top level results, with different parent_ids) top level results with different parent_ids to the first result will be dropped

protected _generateAssociation ( string $type , string $assocKey )

Build an array-based association from string.

protected _isUUIDField ( string $field )

Check if the passed in field is a UUID field

protected _normalizeXmlData ( array $xml )

Normalize <code>Xml::toArray()</code> to use in <code>Model::save()</code>

protected _prepareUpdateFields ( array $data )

Helper method for <code>Model::updateCounterCache()</code>. Checks the fields to be updated for

protected _saveMulti ( array $joined , integer|string $id , DataSource $db )

Saves model hasAndBelongsToMany data to the database.

protected _setAliasData ( array $data )

Move values to alias

public afterDelete ( )

Called after every deletion operation.

public afterFind ( mixed $results , boolean $primary = false )

Called after each find operation. Can be used to modify any results returned by find(). Return value should be the (modified) results.

public afterSave ( boolean $created )

Called after each successful save operation.

public afterValidate ( )

Called after data has been checked for errors

public associations ( )

Get associations

public beforeDelete ( boolean $cascade = true )

Called before every deletion operation.

public beforeFind ( array $queryData )

Called before each find operation. Return false if you want to halt the find call, otherwise return the (modified) query data.

public beforeSave ( array $options = array() )

Called before each save operation, after validation. Return a non-true result to halt the save.

public beforeValidate ( array $options = array() )

Called during validation operations, before validation. Please note that custom validation rules can be defined in $validate.

public bindModel ( array $params , boolean $reset = true )

Bind model associations on the fly.

public buildQuery ( string $type = 'first' , array $query = array() )

Builds the query array that is used by the data source to generate the query to fetch the data.

public create ( boolean|array $data = array() , boolean $filterKey = false )

Initializes the model for writing a new record, loading the default values for those fields that are not defined in $data, and clearing previous validation errors. Especially helpful for saving data in loops.

public deconstruct ( string $field , array|object $data )

Deconstructs a complex data type (array or object) into a single field value.

public delete ( integer|string $id = null , boolean $cascade = true )

Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.

public deleteAll ( mixed $conditions , boolean $cascade = true , boolean $callbacks = false )

Deletes multiple model records based on a set of conditions.

public escapeField ( string $field = null , string $alias = null )

Escapes the field name and prepends the model name. Escaping is done according to the current database driver's rules.

public exists ( integer|string $id = null )

Returns true if a record with particular ID exists.

public field ( string $name , array $conditions = null , string $order = null )

Returns the contents of a single field given the supplied conditions, in the supplied order.

public find ( string $type = 'first' , array $query = array() )

Queries the datasource and returns a result set array.

public getAffectedRows ( )

Returns the number of rows affected by the last query.

public getAssociated ( string $type = null )

Gets all the models with which this model is associated.

public getColumnType ( string $column )

Returns the column type of a column in the model.

public getColumnTypes ( )

Returns an associative array of field names and column types.

public getDataSource ( )

Gets the DataSource to which this model is bound.

public getEventManager ( )

Returns the CakeEventManager manager instance that is handling any callbacks. You can use this instance to register any new listeners or callbacks to the model events, or create your own events and trigger them at will.

public getID ( integer $list = 0 )

Returns the current record's ID

public getInsertID ( )

Returns the ID of the last record this model inserted.

public getLastInsertID ( )

Returns the ID of the last record this model inserted.

public getNumRows ( )

Returns the number of rows returned from the last query.

public getVirtualField ( string $field = null )

Returns the expression for a model virtual field

public hasAny ( array $conditions = null )

Returns true if a record that meets given conditions exists.

public hasField ( string|array $name , boolean $checkVirtual = false )

Returns true if the supplied field exists in the model's database table.

public hasMethod ( string $method )

Check that a method is callable on a model. This will check both the model's own methods, its inherited methods and methods that could be callable through behaviors.

public implementedEvents ( )

Returns a list of all events that will fire in the model during it's lifecycle. You can override this function to add you own listener callbacks

public invalidFields ( string $options = array() )

Returns an array of fields that have failed validation. On the current model.

public invalidate ( string $field , mixed $value = true )

Marks a field as invalid, optionally setting the name of validation rule (in case of multiple validation for field) that was broken.

public isForeignKey ( string $field )

Returns true if given field name is a foreign key in this model.

public isUnique ( array $fields , boolean $or = true )

Returns false if any fields passed match any (by default, all if $or = false) of their matching values.

public isVirtualField ( string $field )

Returns true if the supplied field is a model Virtual Field

public joinModel ( string|array $assoc , array $keys = array() )

Gets the name and fields to be used by a join model. This allows specifying join fields in the association definition.

public onError ( )

Called when a DataSource-level error occurs.

public query ( string $sql )

Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.

public read ( string|array $fields = null , integer|string $id = null )

Returns a list of fields from the database, and sets the current model data (Model::$data) with the record found.

public resetAssociations ( )

This resets the association arrays for the model back to those originally defined in the model. Normally called at the end of each call to Model::find()

public save ( array $data = null , boolean|array $validate = true , array $fieldList = array() )

Saves model data (based on white-list, if supplied) to the database. By default, validation occurs before save.

public saveAll ( array $data = array() , array $options = array() )

Backwards compatible passthrough method for: saveMany(), validateMany(), saveAssociated() and validateAssociated()

public saveAssociated ( array $data = null , array $options = array() )

Saves a single record, as well as all its directly associated records.

public saveField ( string $name , mixed $value , boolean|array $validate = false )

Saves the value of a single field to the database, based on the current model ID.

public saveMany ( array $data = null , array $options = array() )

Saves multiple individual records for a single model

public schema ( boolean|string $field = false )

Returns an array of table metadata (column names and types) from the database. $field =&gt; keys(type, null, default, key, length, extra)

public set ( string|array|SimpleXmlElement|DomNode $one , string $two = null )

This function does two things:

public setDataSource ( string $dataSource = null )

Sets the DataSource to which this model is bound.

public setInsertID ( integer|string $id )

Sets the ID of the last record this model inserted

public setSource ( string $tableName )

Sets a custom table for your model class. Used by your controller to select a database table.

public unbindModel ( array $params , boolean $reset = true )

Turn off associations on the fly.

public updateAll ( array $fields , mixed $conditions = true )

Updates multiple model records based on a set of conditions.

public updateCounterCache ( array $keys = array() , boolean $created = false )

Updates the counter cache of belongsTo associations after a save or delete operation

public validateAssociated ( array & $data , array $options = array() )

Validates a single record, as well as all its directly associated records.

public validateMany ( array & $data , array $options = array() )

Validates multiple individual records for a single model

public validates ( array $options = array() )

Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation.

public validator ( ModelValidator $instance = null )

Returns an instance of a model validator for this class

Method Detail

__call( ) public

Handles custom method calls, like findBy<field> for DB models, and custom RPC calls for remote data sources.

Parameters
string $method
Name of method to call.
array $params
Parameters for the method.
Returns
mixed
Whatever is returned by called method

__construct( ) public

Constructor. Binds the model's database table to the object.

If $id is an array it can be used to pass several options into the model.

  • id: The id to start the model on.
  • table: The table to use for this model.
  • ds: The connection name this model is connected to.
  • name: The name of the model eg. Post.
  • alias: The alias of the model, this is used for registering the instance in the ClassRegistry. eg. ParentThread

Overriding Model's __construct method.

When overriding Model::__construct() be careful to include and pass in all 3 of the arguments to parent::__construct($id, $table, $ds);

Dynamically creating models

You can dynamically create model instances using the $id array syntax.

$Post = new Model(array('table' => 'posts', 'name' => 'Post', 'ds' => 'connection2'));

Would create a model attached to the posts table on connection2. Dynamic model creation is useful when you want a model object that contains no associations or attached behaviors.

Parameters
integer|string|array $id optional false
Set this ID for this model on startup, can also be an array of options, see above.
string $table optional null
Name of database table to use.
string $ds optional null
DataSource connection name.
Overrides
Object::__construct()

__get( ) public

Returns the value of the requested variable if it can be set by __isset()

Parameters
string $name
variable requested for it's value or reference
Returns
mixed
value of requested variable if it is set

__isset( ) public

Handles the lazy loading of model associations by looking in the association arrays for the requested variable

Parameters
string $name
variable tested for existence in class
Returns
boolean
true if the variable exists (if is a not loaded model association it will be created), false otherwise

_addToWhiteList( ) protected

Helper method for saveAll() and friends, to add foreign key to fieldlist

Parameters
string $key
fieldname to be added to list
array $options
Returns
array
$options

_clearCache( ) protected

Clears cache for this model.

Parameters
string $type optional null
If null this deletes cached views if Cache.check is true Will be used to allow deleting query cache also
Returns
boolean
true on delete

_collectForeignKeys( ) protected

Collects foreign keys from associations.

Parameters
string $type optional 'belongsTo'
Returns
array
array

_constructLinkedModel( ) protected

Protected helper method to create associated models of a given class.

Parameters
string $assoc
Association name
string $className optional null
Class name
string $plugin optional null
name of the plugin where $className is located examples: public $hasMany = array('Assoc' =&gt; array('className' =&gt; 'ModelName')); usage: $this-&gt;Assoc-&gt;modelMethods(); public $hasMany = array('ModelName'); usage: $this-&gt;ModelName-&gt;modelMethods();

_createLinks( ) protected

Create a set of associations.

_deleteDependent( ) protected

Cascades model deletes through associated hasMany and hasOne child records.

Parameters
string $id
ID of record that was deleted
boolean $cascade
Set to true to delete records that depend on this record

_deleteLinks( ) protected

Cascades model deletes through HABTM join keys.

Parameters
string $id
ID of record that was deleted

_filterResults( ) protected

Passes query results through model and behavior afterFilter() methods.

Parameters
array $results
Results to filter
boolean $primary optional true
If this is the primary model results (results from model where the find operation was performed)
Returns
array
Set of filtered results

_findCount( ) protected

Handles the before/after filter logic for find('count') operations. Only called by Model::find().

Parameters
string $state
Either "before" or "after"
array $query
array $results optional array()
Returns
integer
The number of records found, or false
See
Model::find()

_findFirst( ) protected

Handles the before/after filter logic for find('first') operations. Only called by Model::find().

Parameters
string $state
Either "before" or "after"
array $query
array $results optional array()
Returns
array
array
See
Model::find()

_findList( ) protected

Handles the before/after filter logic for find('list') operations. Only called by Model::find().

Parameters
string $state
Either "before" or "after"
array $query
array $results optional array()
Returns
array
Key/value pairs of primary keys/display field values of all records found
See
Model::find()

_findNeighbors( ) protected

Detects the previous field's value, then uses logic to find the 'wrapping' rows and return them.

Parameters
string $state
Either "before" or "after"
array $query
array $results optional array()
Returns
array
array

_findThreaded( ) protected

In the event of ambiguous results returned (multiple top level results, with different parent_ids) top level results with different parent_ids to the first result will be dropped

Parameters
string $state
mixed $query
array $results optional array()
Returns
array
Threaded results

_generateAssociation( ) protected

Build an array-based association from string.

Parameters
string $type
'belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany'
string $assocKey

_isUUIDField( ) protected

Check if the passed in field is a UUID field

Parameters
string $field
the field to check
Returns
boolean
boolean

_normalizeXmlData( ) protected

Normalize Xml::toArray() to use in Model::save()

Parameters
array $xml
XML as array
Returns
array
array

_prepareUpdateFields( ) protected

Helper method for Model::updateCounterCache(). Checks the fields to be updated for

Parameters
array $data
The fields of the record that will be updated
Returns
array
Returns updated foreign key values, along with an 'old' key containing the old values, or empty if no foreign keys are updated.

_saveMulti( ) protected

Saves model hasAndBelongsToMany data to the database.

Parameters
array $joined
Data to save
integer|string $id
ID of record in this model
DataSource $db

_setAliasData( ) protected

Move values to alias

Parameters
array $data
Returns
array
array

afterDelete( ) public

Called after every deletion operation.

Link
http://book.cakephp.org/2.0/en/models/callback-methods.html#afterdelete

afterFind( ) public

Called after each find operation. Can be used to modify any results returned by find(). Return value should be the (modified) results.

Parameters
mixed $results
The results of the find operation
boolean $primary optional false
Whether this model is being queried directly (vs. being queried as an association)
Returns
mixed
Result of the find operation
Link
http://book.cakephp.org/2.0/en/models/callback-methods.html#afterfind

afterSave( ) public

Called after each successful save operation.

Parameters
boolean $created
True if this save created a new record
Link
http://book.cakephp.org/2.0/en/models/callback-methods.html#aftersave

afterValidate( ) public

Called after data has been checked for errors

associations( ) public

Get associations

Returns
array
array

beforeDelete( ) public

Called before every deletion operation.

Parameters
boolean $cascade optional true
If true records that depend on this record will also be deleted
Returns
boolean
True if the operation should continue, false if it should abort
Link
http://book.cakephp.org/2.0/en/models/callback-methods.html#beforedelete

beforeFind( ) public

Called before each find operation. Return false if you want to halt the find call, otherwise return the (modified) query data.

Parameters
array $queryData
Data used to execute this query, i.e. conditions, order, etc.
Returns
mixed
true if the operation should continue, false if it should abort; or, modified $queryData to continue with new $queryData
Link
http://book.cakephp.org/2.0/en/models/callback-methods.html#beforefind

beforeSave( ) public

Called before each save operation, after validation. Return a non-true result to halt the save.

Parameters
array $options optional array()
Returns
boolean
True if the operation should continue, false if it should abort
Link
http://book.cakephp.org/2.0/en/models/callback-methods.html#beforesave

beforeValidate( ) public

Called during validation operations, before validation. Please note that custom validation rules can be defined in $validate.

Parameters
array $options optional array()
Options passed from model::save(), see $options of model::save().
Returns
boolean
True if validate operation should continue, false to abort
Link
http://book.cakephp.org/2.0/en/models/callback-methods.html#beforevalidate

bindModel( ) public

Bind model associations on the fly.

If $reset is false, association will not be reset to the originals defined in the model

Example: Add a new hasOne binding to the Profile model not defined in the model source code:

$this->User->bindModel( array('hasOne' => array('Profile')) );

Bindings that are not made permanent will be reset by the next Model::find() call on this model.

Parameters
array $params
Set of bindings (indexed by binding type)
boolean $reset optional true
Set to false to make the binding permanent
Returns
boolean
Success
Link
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly

buildQuery( ) public

Builds the query array that is used by the data source to generate the query to fetch the data.

Parameters
string $type optional 'first'
Type of find operation (all / first / count / neighbors / list / threaded)
array $query optional array()
Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
Returns
array
Query array or null if it could not be build for some reasons
See
Model::find()

create( ) public

Initializes the model for writing a new record, loading the default values for those fields that are not defined in $data, and clearing previous validation errors. Especially helpful for saving data in loops.

Parameters
boolean|array $data optional array()
Optional data array to assign to the model after it is created. If null or false, schema data defaults are not merged.
boolean $filterKey optional false
If true, overwrites any primary key input with an empty value
Returns
array
The current Model::data; after merging $data and/or defaults from database
Link
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-create-array-data-array

deconstruct( ) public

Deconstructs a complex data type (array or object) into a single field value.

Parameters
string $field
The name of the field to be deconstructed
array|object $data
An array or object to be deconstructed into a field
Returns
mixed
The resulting data that should be assigned to a field

delete( ) public

Removes record for given ID. If no ID is given, the current ID is used. Returns true on success.

Parameters
integer|string $id optional null
ID of record to delete
boolean $cascade optional true
Set to true to delete records that depend on this record
Returns
boolean
True on success
Link
http://book.cakephp.org/2.0/en/models/deleting-data.html

deleteAll( ) public

Deletes multiple model records based on a set of conditions.

Parameters
mixed $conditions
Conditions to match
boolean $cascade optional true
Set to true to delete records that depend on this record
boolean $callbacks optional false
Run callbacks
Returns
boolean
True on success, false on failure
Link
http://book.cakephp.org/2.0/en/models/deleting-data.html#deleteall

escapeField( ) public

Escapes the field name and prepends the model name. Escaping is done according to the current database driver's rules.

Parameters
string $field optional null
Field to escape (e.g: id)
string $alias optional null
Alias for the model (e.g: Post)
Returns
string
The name of the escaped field for this Model (i.e. id becomes Post.id).

exists( ) public

Returns true if a record with particular ID exists.

If $id is not passed it calls Model::getID() to obtain the current record ID, and then performs a Model::find('count') on the currently configured datasource to ascertain the existence of the record in persistent storage.

Parameters
integer|string $id optional null
ID of record to check for existence
Returns
boolean
True if such a record exists

field( ) public

Returns the contents of a single field given the supplied conditions, in the supplied order.

Parameters
string $name
Name of field to get
array $conditions optional null
SQL conditions (defaults to NULL)
string $order optional null
SQL ORDER BY fragment
Returns
string
field contents, or false if not found
Link
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-field

find( ) public

Queries the datasource and returns a result set array.

Used to perform find operations, where the first argument is type of find operation to perform (all / first / count / neighbors / list / threaded), second parameter options for finding ( indexed array, including: 'conditions', 'limit', 'recursive', 'page', 'fields', 'offset', 'order', 'callbacks')

Eg:

$model->find('all', array(
  'conditions' => array('name' => 'Thomas Anderson'),
  'fields' => array('name', 'email'),
  'order' => 'field3 DESC',
  'recursive' => 2,
  'group' => 'type',
  'callbacks' => false,
));

In addition to the standard query keys above, you can provide Datasource, and behavior specific keys. For example, when using a SQL based datasource you can use the joins key to specify additional joins that should be part of the query.

$model->find('all', array(
  'conditions' => array('name' => 'Thomas Anderson'),
  'joins' => array(
    array(
      'alias' => 'Thought',
      'table' => 'thoughts',
      'type' => 'LEFT',
      'conditions' => '`Thought`.`person_id` = `Person`.`id`'
    )
  )
));

Disabling callbacks

The callbacks key allows you to disable or specify the callbacks that should be run. To disable beforeFind & afterFind callbacks set 'callbacks' => false in your options. You can also set the callbacks option to 'before' or 'after' to enable only the specified callback.

Adding new find types

Behaviors and find types can also define custom finder keys which are passed into find(). See the documentation for custom find types (http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#creating-custom-find-types) for how to implement custom find types.

Specifying 'fields' for notation 'list':

  • If no fields are specified, then 'id' is used for key and 'model->displayField' is used for value.
  • If a single field is specified, 'id' is used for key and specified field is used for value.
  • If three fields are specified, they are used (in order) for key, value and group.
  • Otherwise, first and second fields are used for key and value.

Note: find(list) + database views have issues with MySQL 5.0. Try upgrading to MySQL 5.1 if you have issues with database views.

Note: find(count) has its own return values.

Parameters
string $type optional 'first'
Type of find operation (all / first / count / neighbors / list / threaded)
array $query optional array()
Option fields (conditions / fields / joins / limit / offset / order / page / group / callbacks)
Returns
array
Array of records, or Null on failure.
Link
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html

getAffectedRows( ) public

Returns the number of rows affected by the last query.

Returns
integer
Number of rows

getAssociated( ) public

Gets all the models with which this model is associated.

Parameters
string $type optional null
Only result associations of this type
Returns
array
Associations

getColumnType( ) public

Returns the column type of a column in the model.

Parameters
string $column
The name of the model column
Returns
string
Column type

getColumnTypes( ) public

Returns an associative array of field names and column types.

Returns
array
Field types indexed by field name

getDataSource( ) public

Gets the DataSource to which this model is bound.

Returns
DataSource
A DataSource object

getEventManager( ) public

Returns the CakeEventManager manager instance that is handling any callbacks. You can use this instance to register any new listeners or callbacks to the model events, or create your own events and trigger them at will.

Returns
CakeEventManager
CakeEventManager

getID( ) public

Returns the current record's ID

Parameters
integer $list optional 0
Index on which the composed ID is located
Returns
mixed
The ID of the current record, false if no ID

getInsertID( ) public

Returns the ID of the last record this model inserted.

Returns
mixed
Last inserted ID

getLastInsertID( ) public

Returns the ID of the last record this model inserted.

Returns
mixed
Last inserted ID

getNumRows( ) public

Returns the number of rows returned from the last query.

Returns
integer
Number of rows

getVirtualField( ) public

Returns the expression for a model virtual field

Parameters
string $field optional null
Name of field to look for
Returns
mixed
If $field is string expression bound to virtual field $field If $field is null, returns an array of all model virtual fields or false if none $field exist.

hasAny( ) public

Returns true if a record that meets given conditions exists.

Parameters
array $conditions optional null
SQL conditions array
Returns
boolean
True if such a record exists

hasField( ) public

Returns true if the supplied field exists in the model's database table.

Parameters
string|array $name
Name of field to look for, or an array of names
boolean $checkVirtual optional false
checks if the field is declared as virtual
Returns
mixed
If $name is a string, returns a boolean indicating whether the field exists. If $name is an array of field names, returns the first field that exists, or false if none exist.

hasMethod( ) public

Check that a method is callable on a model. This will check both the model's own methods, its inherited methods and methods that could be callable through behaviors.

Parameters
string $method
The method to be called.
Returns
boolean
True on method being callable.

implementedEvents( ) public

Returns a list of all events that will fire in the model during it's lifecycle. You can override this function to add you own listener callbacks

Returns
array
array
Implementation of
CakeEventListener::implementedEvents()

invalidFields( ) public

Returns an array of fields that have failed validation. On the current model.

Parameters
string $options optional array()
An optional array of custom options to be made available in the beforeValidate callback
Returns
array
Array of invalid fields
See
Model::validates()

invalidate( ) public

Marks a field as invalid, optionally setting the name of validation rule (in case of multiple validation for field) that was broken.

Parameters
string $field
The name of the field to invalidate
mixed $value optional true
Name of validation rule that was not failed, or validation message to be returned. If no validation key is provided, defaults to true.

isForeignKey( ) public

Returns true if given field name is a foreign key in this model.

Parameters
string $field
Returns true if the input string ends in "_id"
Returns
boolean
True if the field is a foreign key listed in the belongsTo array.

isUnique( ) public

Returns false if any fields passed match any (by default, all if $or = false) of their matching values.

Parameters
array $fields
Field/value pairs to search (if no values specified, they are pulled from $this-&gt;data)
boolean $or optional true
If false, all fields specified must match in order for a false return value
Returns
boolean
False if any records matching any fields are found

isVirtualField( ) public

Returns true if the supplied field is a model Virtual Field

Parameters
string $field
Name of field to look for
Returns
boolean
indicating whether the field exists as a model virtual field.

joinModel( ) public

Gets the name and fields to be used by a join model. This allows specifying join fields in the association definition.

Parameters
string|array $assoc
The model to be joined
array $keys optional array()
Any join keys which must be merged with the keys queried
Returns
array
array

onError( ) public

Called when a DataSource-level error occurs.

Link
http://book.cakephp.org/2.0/en/models/callback-methods.html#onerror

query( ) public

Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.

Parameters
string $sql
SQL statement
Returns
mixed
Resultset array or boolean indicating success / failure depending on the query executed
Link
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-query

read( ) public

Returns a list of fields from the database, and sets the current model data (Model::$data) with the record found.

Parameters
string|array $fields optional null
String of single field name, or an array of field names.
integer|string $id optional null
The ID of the record to read
Returns
array
Array of database fields, or false if not found
Link
http://book.cakephp.org/2.0/en/models/retrieving-your-data.html#model-read

resetAssociations( ) public

This resets the association arrays for the model back to those originally defined in the model. Normally called at the end of each call to Model::find()

Returns
boolean
Success

save( ) public

Saves model data (based on white-list, if supplied) to the database. By default, validation occurs before save.

Parameters
array $data optional null
Data to save.
boolean|array $validate optional true
Either a boolean, or an array. If a boolean, indicates whether or not to validate before saving. If an array, can have following keys: - validate: Set to true/false to enable or disable validation. - fieldList: An array of fields you want to allow for saving. - callbacks: Set to false to disable callbacks. Using 'before' or 'after' will enable only those callbacks.
array $fieldList optional array()
List of fields to allow to be saved
Returns
mixed
On success Model::$data if its not empty or true, false on failure
Link
http://book.cakephp.org/2.0/en/models/saving-your-data.html

saveAll( ) public

Backwards compatible passthrough method for: saveMany(), validateMany(), saveAssociated() and validateAssociated()

Saves multiple individual records for a single model; Also works with a single record, as well as all its associated records.

Options

  • validate: Set to false to disable validation, true to validate each record before saving, 'first' to validate all records before any are saved (default), or 'only' to only validate the records, but not save them.
  • atomic: If true (default), will attempt to save all records in a single transaction. Should be set to false if database/table does not support transactions.
  • fieldList: Equivalent to the $fieldList parameter in Model::save(). It should be an associate array with model name as key and array of fields as value. Eg.
    array(
        'SomeModel' => array('field'),
        'AssociatedModel' => array('field', 'otherfield')
    )
    
  • deep: see saveMany/saveAssociated
Parameters
array $data optional array()
Record data to save. This can be either a numerically-indexed array (for saving multiple records of the same type), or an array indexed by association name.
array $options optional array()
Options to use when saving record data, See $options above.
Returns
mixed
If atomic: True on success, or false on failure. Otherwise: array similar to the $data array passed, but values are set to true/false depending on whether each record saved successfully.
Link
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveall-array-data-null-array-options-array

saveAssociated( ) public

Saves a single record, as well as all its directly associated records.

Options

  • validate: Set to false to disable validation, true to validate each record before saving, 'first' to validate all records before any are saved(default),
  • atomic: If true (default), will attempt to save all records in a single transaction. Should be set to false if database/table does not support transactions.
  • fieldList: Equivalent to the $fieldList parameter in Model::save(). It should be an associate array with model name as key and array of fields as value. Eg.
    array(
        'SomeModel' => array('field'),
        'AssociatedModel' => array('field', 'otherfield')
    )
    
  • deep: If set to true, not only directly associated data is saved, but deeper nested associated data as well.
Parameters
array $data optional null
Record data to save. This should be an array indexed by association name.
array $options optional array()
Options to use when saving record data, See $options above.
Returns
mixed
If atomic: True on success, or false on failure. Otherwise: array similar to the $data array passed, but values are set to true/false depending on whether each record saved successfully.
Link
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-saveassociated-array-data-null-array-options-array

saveField( ) public

Saves the value of a single field to the database, based on the current model ID.

Parameters
string $name
Name of the table field
mixed $value
Value of the field
boolean|array $validate optional false
Either a boolean, or an array. If a boolean, indicates whether or not to validate before saving. If an array, allows control of 'validate' and 'callbacks' options.
Returns
boolean
See Model::save()
See
Model::save()
Link
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savefield-string-fieldname-string-fieldvalue-validate-false

saveMany( ) public

Saves multiple individual records for a single model

Options

  • validate: Set to false to disable validation, true to validate each record before saving, 'first' to validate all records before any are saved (default),
  • atomic: If true (default), will attempt to save all records in a single transaction. Should be set to false if database/table does not support transactions.
  • fieldList: Equivalent to the $fieldList parameter in Model::save()
  • deep: If set to true, all associated data will be saved as well.
Parameters
array $data optional null
Record data to save. This should be a numerically-indexed array
array $options optional array()
Options to use when saving record data, See $options above.
Returns
mixed
If atomic: True on success, or false on failure. Otherwise: array similar to the $data array passed, but values are set to true/false depending on whether each record saved successfully.
Link
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-savemany-array-data-null-array-options-array

schema( ) public

Returns an array of table metadata (column names and types) from the database. $field => keys(type, null, default, key, length, extra)

Parameters
boolean|string $field optional false
Set to true to reload schema, or a string to return a specific field
Returns
array
Array of table metadata

set( ) public

This function does two things:

1. it scans the array $one for the primary key, and if that's found, it sets the current id to the value of $one[id]. For all other keys than 'id' the keys and values of $one are copied to the 'data' property of this object. 2. Returns an array with all of $one's keys and values. (Alternative indata: two strings, which are mangled to a one-item, two-dimensional array using $one for a key and $two as its value.)

Parameters
string|array|SimpleXmlElement|DomNode $one
Array or string of data
string $two optional null
Value string for the alternative indata method
Returns
array
Data with all of $one's keys and values
Link
http://book.cakephp.org/2.0/en/models/saving-your-data.html

setDataSource( ) public

Sets the DataSource to which this model is bound.

Parameters
string $dataSource optional null
The name of the DataSource, as defined in app/Config/database.php
Throws
MissingConnectionException
MissingConnectionException

setInsertID( ) public

Sets the ID of the last record this model inserted

Parameters
integer|string $id
Last inserted ID

setSource( ) public

Sets a custom table for your model class. Used by your controller to select a database table.

Parameters
string $tableName
Name of the custom table
Throws
MissingTableException
when database table $tableName is not found on data source

unbindModel( ) public

Turn off associations on the fly.

If $reset is false, association will not be reset to the originals defined in the model

Example: Turn off the associated Model Support request, to temporarily lighten the User model:

$this->User->unbindModel( array('hasMany' => array('Supportrequest')) );

unbound models that are not made permanent will reset with the next call to Model::find()

Parameters
array $params
Set of bindings to unbind (indexed by binding type)
boolean $reset optional true
Set to false to make the unbinding permanent
Returns
boolean
Success
Link
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#creating-and-destroying-associations-on-the-fly

updateAll( ) public

Updates multiple model records based on a set of conditions.

Parameters
array $fields
Set of fields and values, indexed by fields. Fields are treated as SQL snippets, to insert literal values manually escape your data.
mixed $conditions optional true
Conditions to match, true for all records
Returns
boolean
True on success, false on failure
Link
http://book.cakephp.org/2.0/en/models/saving-your-data.html#model-updateall-array-fields-array-conditions

updateCounterCache( ) public

Updates the counter cache of belongsTo associations after a save or delete operation

Parameters
array $keys optional array()
Optional foreign key data, defaults to the information $this-&gt;data
boolean $created optional false
True if a new record was created, otherwise only associations with 'counterScope' defined get updated

validateAssociated( ) public

Validates a single record, as well as all its directly associated records.

Options

  • atomic: If true (default), returns boolean. If false returns array.
  • fieldList: Equivalent to the $fieldList parameter in Model::save()
  • deep: If set to true, not only directly associated data , but deeper nested associated data is validated as well.

Warning: This method could potentially change the passed argument $data, If you do not want this to happen, make a copy of $data before passing it to this method

Parameters
array $data
Record data to validate. This should be an array indexed by association name.
array $options optional array()
Options to use when validating record data (see above), See also $options of validates().
Returns
array|boolean
If atomic: True on success, or false on failure. Otherwise: array similar to the $data array passed, but values are set to true/false depending on whether each record validated successfully.

validateMany( ) public

Validates multiple individual records for a single model

Options

  • atomic: If true (default), returns boolean. If false returns array.
  • fieldList: Equivalent to the $fieldList parameter in Model::save()
  • deep: If set to true, all associated data will be validated as well.

Warning: This method could potentially change the passed argument $data, If you do not want this to happen, make a copy of $data before passing it to this method

Parameters
array $data
Record data to validate. This should be a numerically-indexed array
array $options optional array()
Options to use when validating record data (see above), See also $options of validates().
Returns
boolean|array
If atomic: True on success, or false on failure. Otherwise: array similar to the $data array passed, but values are set to true/false depending on whether each record validated successfully.

validates( ) public

Returns true if all fields pass validation. Will validate hasAndBelongsToMany associations that use the 'with' key as well. Since _saveMulti is incapable of exiting a save operation.

Will validate the currently set data. Use Model::set() or Model::create() to set the active data.

Parameters
array $options optional array()
An optional array of custom options to be made available in the beforeValidate callback
Returns
boolean
True if there are no errors

validator( ) public

Returns an instance of a model validator for this class

Parameters
ModelValidator $instance optional null
validator instance. If null a new ModelValidator instance will be made using current model object
Returns
ModelValidator
ModelValidator

Methods inherited from Object

_mergeVars(), _set(), _stop(), dispatchMethod(), log(), requestAction(), toString()

Properties summary

public BehaviorCollection $Behaviors

Holds the Behavior objects currently bound to this model.

null
public array $__backAssociation

Holds model associations temporarily to allow for dynamic (un)binding.

array()
public array $__backContainableAssociation

Back containable association

array()
public array $__backInnerAssociation

Back inner association

array()
public array $__backOriginalAssociation

Back original association

array()
protected array $_associationKeys

Default list of association keys.

array(
    'belongsTo' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'counterCache'),
    'hasOne' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'dependent'),
    'hasMany' => array('className', 'foreignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'dependent', 'exclusive', 'finderQuery', 'counterQuery'),
    'hasAndBelongsToMany' => array('className', 'joinTable', 'with', 'foreignKey', 'associationForeignKey', 'conditions', 'fields', 'order', 'limit', 'offset', 'unique', 'finderQuery', 'deleteQuery', 'insertQuery')
)
protected array $_associations

Holds provided/generated association key names and other data for all associations.

array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany')
protected CakeEventManager $_eventManager

Instance of the CakeEventManager this model is using to dispatch inner events.

null
protected integer $_insertID

The ID of the model record that was last inserted.

null
protected array $_schema

Field-by-field table metadata.

null
protected boolean $_sourceConfigured

Has the datasource been configured.

See
Model::getDataSource()
false
protected ModelValidator $_validator

Instance of the ModelValidator

null
public array $actsAs

List of behaviors to load when the model object is initialized. Settings can be passed to behaviors by using the behavior name as index. Eg:

public $actsAs = array('Translate', 'MyBehavior' => array('setting1' => 'value1'))

Link
http://book.cakephp.org/2.0/en/models/behaviors.html#using-behaviors
null
public string $alias

Alias name for model.

null
public array $belongsTo

Detailed list of belongsTo associations.

Basic usage

public $belongsTo = array('Group', 'Department');

Detailed configuration

public $belongsTo = array(
    'Group',
    'Department' => array(
        'className' => 'Department',
        'foreignKey' => 'department_id'
    )
);

Possible keys in association

  • className: the classname of the model being associated to the current model. If you're defining a 'Profile belongsTo User' relationship, the className key should equal 'User.'
  • foreignKey: the name of the foreign key found in the current model. This is especially handy if you need to define multiple belongsTo relationships. The default value for this key is the underscored, singular name of the other model, suffixed with '_id'.
  • conditions: An SQL fragment used to filter related model records. It's good practice to use model names in SQL fragments: 'User.active = 1' is always better than just 'active = 1.'
  • type: the type of the join to use in the SQL query, default is LEFT which may not fit your needs in all situations, INNER may be helpful when you want everything from your main and associated models or nothing at all!(effective when used with some conditions of course). (NB: type value is in lower case - i.e. left, inner)
  • fields: A list of fields to be retrieved when the associated model data is fetched. Returns all fields by default.
  • order: An SQL fragment that defines the sorting order for the returned associated rows.
  • counterCache: If set to true the associated Model will automatically increase or decrease the "[singular_model_name]_count" field in the foreign table whenever you do a save() or delete(). If its a string then its the field name to use. The value in the counter field represents the number of related rows.
  • counterScope: Optional conditions array to use for updating counter cache field.
Link
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#belongsto
array()
public boolean $cacheQueries

Whether or not to cache queries for this model. This enables in-memory caching only, the results are not stored beyond the current request.

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#cachequeries
false
public boolean $cacheSources

Whether or not to cache sources for this model.

true
public array $data

Container for the data that this model gets from persistent storage (usually, a database).

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#data
array()
public string $displayField

Custom display field name. Display fields are used by Scaffold, in SELECT boxes' OPTION elements.

This field is also used in find('list') when called with no extra parameters in the fields list

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#displayfield
null
public array $findMethods

List of valid finder method options, supplied as the first parameter to find().

array(
    'all' => true, 'first' => true, 'count' => true,
    'neighbors' => true, 'list' => true, 'threaded' => true
)
public string $findQueryType

Type of find query currently executing.

null
public array $hasAndBelongsToMany

Detailed list of hasAndBelongsToMany associations.

Basic usage

public $hasAndBelongsToMany = array('Role', 'Address');

Detailed configuration

public $hasAndBelongsToMany = array(
    'Role',
    'Address' => array(
        'className' => 'Address',
        'foreignKey' => 'user_id',
        'associationForeignKey' => 'address_id',
        'joinTable' => 'addresses_users'
    )
);

Possible keys in association

  • className: the classname of the model being associated to the current model. If you're defining a 'Recipe HABTM Tag' relationship, the className key should equal 'Tag.'
  • joinTable: The name of the join table used in this association (if the current table doesn't adhere to the naming convention for HABTM join tables).
  • with: Defines the name of the model for the join table. By default CakePHP will auto-create a model for you. Using the example above it would be called RecipesTag. By using this key you can override this default name. The join table model can be used just like any "regular" model to access the join table directly.
  • foreignKey: the name of the foreign key found in the current model. This is especially handy if you need to define multiple HABTM relationships. The default value for this key is the underscored, singular name of the current model, suffixed with '_id'.
  • associationForeignKey: the name of the foreign key found in the other model. This is especially handy if you need to define multiple HABTM relationships. The default value for this key is the underscored, singular name of the other model, suffixed with '_id'.
  • unique: If true (default value) cake will first delete existing relationship records in the foreign keys table before inserting new ones, when updating a record. So existing associations need to be passed again when updating. To prevent deletion of existing relationship records, set this key to a string 'keepExisting'.
  • conditions: An SQL fragment used to filter related model records. It's good practice to use model names in SQL fragments: "Comment.status = 1" is always better than just "status = 1."
  • fields: A list of fields to be retrieved when the associated model data is fetched. Returns all fields by default.
  • order: An SQL fragment that defines the sorting order for the returned associated rows.
  • limit: The maximum number of associated rows you want returned.
  • offset: The number of associated rows to skip over (given the current conditions and order) before fetching and associating.
  • finderQuery, deleteQuery, insertQuery: A complete SQL query CakePHP can use to fetch, delete, or create new associated model records. This should be used in situations that require very custom results.
Link
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasandbelongstomany-habtm
array()
public array $hasMany

Detailed list of hasMany associations.

Basic usage

public $hasMany = array('Comment', 'Task');

Detailed configuration

public $hasMany = array(
    'Comment',
    'Task' => array(
        'className' => 'Task',
        'foreignKey' => 'user_id'
    )
);

Possible keys in association

  • className: the classname of the model being associated to the current model. If you're defining a 'User hasMany Comment' relationship, the className key should equal 'Comment.'
  • foreignKey: the name of the foreign key found in the other model. This is especially handy if you need to define multiple hasMany relationships. The default value for this key is the underscored, singular name of the actual model, suffixed with '_id'.
  • conditions: An SQL fragment used to filter related model records. It's good practice to use model names in SQL fragments: "Comment.status = 1" is always better than just "status = 1."
  • fields: A list of fields to be retrieved when the associated model data is fetched. Returns all fields by default.
  • order: An SQL fragment that defines the sorting order for the returned associated rows.
  • limit: The maximum number of associated rows you want returned.
  • offset: The number of associated rows to skip over (given the current conditions and order) before fetching and associating.
  • dependent: When dependent is set to true, recursive model deletion is possible. In this example, Comment records will be deleted when their associated User record has been deleted.
  • exclusive: When exclusive is set to true, recursive model deletion does the delete with a deleteAll() call, instead of deleting each entity separately. This greatly improves performance, but may not be ideal for all circumstances.
  • finderQuery: A complete SQL query CakePHP can use to fetch associated model records. This should be used in situations that require very custom results.
Link
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasmany
array()
public array $hasOne

Detailed list of hasOne associations.

Basic usage

public $hasOne = array('Profile', 'Address');

Detailed configuration

public $hasOne = array(
    'Profile',
    'Address' => array(
        'className' => 'Address',
        'foreignKey' => 'user_id'
    )
);

Possible keys in association

  • className: the classname of the model being associated to the current model. If you're defining a 'User hasOne Profile' relationship, the className key should equal 'Profile.'
  • foreignKey: the name of the foreign key found in the other model. This is especially handy if you need to define multiple hasOne relationships. The default value for this key is the underscored, singular name of the current model, suffixed with '_id'. In the example above it would default to 'user_id'.
  • conditions: An SQL fragment used to filter related model records. It's good practice to use model names in SQL fragments: "Profile.approved = 1" is always better than just "approved = 1."
  • fields: A list of fields to be retrieved when the associated model data is fetched. Returns all fields by default.
  • order: An SQL fragment that defines the sorting order for the returned associated rows.
  • dependent: When the dependent key is set to true, and the model's delete() method is called with the cascade parameter set to true, associated model records are also deleted. In this case we set it true so that deleting a User will also delete her associated Profile.
Link
http://book.cakephp.org/2.0/en/models/associations-linking-models-together.html#hasone
array()
public mixed $id

Value of the primary key ID of the record that this model is currently pointing to. Automatically set after database insertions.

false
public string $name

Name of the model.

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#name
null
public string $order

The column name(s) and direction(s) to order find results by default.

public $order = "Post.created DESC"; public $order = array("Post.view_count DESC", "Post.rating DESC");

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#order
null
public string $plugin

Plugin model belongs to.

null
public string $primaryKey

The name of the primary key field for this model.

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#primaryKey
null
public integer $recursive

Number of associations to recurse through during find calls. Fetches only the first level by default.

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#recursive
1
public string $schemaName

Holds physical schema/database name for this model. Automatically set during Model creation.

null
public string $table

Table name for this Model.

false
public string $tablePrefix

Database table prefix for tables in model.

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#tableprefix
null
public array $tableToModel

List of table names included in the model description. Used for associations.

array()
public string $useDbConfig

The name of the DataSource connection that this Model uses

The value must be an attribute name that you defined in app/Config/database.php or created using ConnectionManager::create().

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#usedbconfig
'default'
public string $useTable

Custom database table name, or null/false if no table association is desired.

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#usetable
null
public array $validate

List of validation rules. It must be an array with the field name as key and using as value one of the following possibilities

Validating using regular expressions

public $validate = array(
    'name' => '/^[a-z].+$/i'
);

Validating using methods (no parameters)

public $validate = array(
    'name' => 'notEmpty'
);

Validating using methods (with parameters)

public $validate = array(
    'age' => array(
        'rule' => array('between', 5, 25)
    )
);

Validating using custom method

public $validate = array(
    'password' => array(
        'rule' => array('customValidation')
    )
);
public function customValidation($data) {
    // $data will contain array('password' => 'value')
    if (isset($this->data[$this->alias]['password2'])) {
        return $this->data[$this->alias]['password2'] === current($data);
    }
    return true;
}

Validations with messages

The messages will be used in Model::$validationErrors and can be used in the FormHelper

public $validate = array(
    'age' => array(
        'rule' => array('between', 5, 25),
        'message' => array('The age must be between %d and %d.')
    )
);

Multiple validations to the same field

public $validate = array(
    'login' => array(
        array(
            'rule' => 'alphaNumeric',
            'message' => 'Only alphabets and numbers allowed',
            'last' => true
        ),
        array(
            'rule' => array('minLength', 8),
            'message' => array('Minimum length of %d characters')
        )
    )
);

Valid keys in validations

  • rule: String with method name, regular expression (started by slash) or array with method and parameters
  • message: String with the message or array if have multiple parameters. See http://php.net/sprintf
  • last: Boolean value to indicate if continue validating the others rules if the current fail [Default: true]
  • required: Boolean value to indicate if the field must be present on save
  • allowEmpty: Boolean value to indicate if the field can be empty
  • on: Possible values: update, create. Indicate to apply this rule only on update or create
Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#validate
http://book.cakephp.org/2.0/en/models/data-validation.html
array()
public string $validationDomain

Name of the validation string domain to use when translating validation errors.

null
public array $validationErrors

List of validation errors.

array()
public array $virtualFields

Array of virtual fields this model has. Virtual fields are aliased SQL expressions. Fields added to this property will be read as other fields in a model but will not be saveable.

public $virtualFields = array('two' => '1 + 1');

Is a simplistic example of how to set virtualFields

Link
http://book.cakephp.org/2.0/en/models/model-attributes.html#virtualfields
array()
public array $whitelist

Whitelist of fields allowed to be saved.

array()
CakePHP API documentation generated by ApiGen 3.0dev