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.
$Behaviors
public $__backAssociation
public array
array
$__backInnerAssociation
public array
$__backOriginalAssociation
public array
$__safeUpdateMode
public boolean
Safe update mode If true, this prevents Model::save() from generating a query with WHERE 1 = 1 on race condition.
$_associationKeys
protected array
$_associations
protected array
$_eventManager
protected Instance of the CakeEventManager this model is using to dispatch inner events.
$_insertID
protected integer
$_schema
protected array
$_sourceConfigured
protected boolean
$_validator
protected $actsAs
public array
List of behaviors to load when the model object is initialized. Settings can be passed to behaviors by using the behavior name as index.
$alias
public string
$belongsTo
public array
$cacheQueries
public boolean
Whether or not to cache queries for this model. This enables in-memory caching only, the results are not stored beyond the current request.
$cacheSources
public boolean
$data
public array
$displayField
public string
$findMethods
public array
$findQueryType
public string
$hasAndBelongsToMany
public array
$hasMany
public array
$hasOne
public array
$id
public mixed
Value of the primary key ID of the record that this model is currently pointing to. Automatically set after database insertions.
$name
public string
$order
public string
$plugin
public string
$primaryKey
public string
$recursive
public integer
Number of associations to recurse through during find calls. Fetches only the first level by default.
$schemaName
public string
$table
public string
$tablePrefix
public string
$tableToModel
public array
$useConsistentAfterFind
public boolean
If true, afterFind will be passed consistent formatted $results in case of $primary is false. The format will be such as the following.
$useDbConfig
public string
$useTable
public string
$validate
public array
List of validation rules. It must be an array with the field name as key and using as value one of the following possibilities
$validationDomain
public string
$validationErrors
public array
$virtualFields
public array
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.
$whitelist
public array
Handles custom method calls, like findBy
Saves model data (based on white-list, if supplied) to the database. By default, validation occurs before save.
Detects the previous field's value, then uses logic to find the 'wrapping' rows and return them.
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
Xml::toArray()
to use in Model::save()
Model::updateCounterCache()
. Checks the fields to be updated for Called after each find operation. Can be used to modify any results returned by find(). Return value should be the (modified) results.
Called before each find operation. Return false if you want to halt the find call, otherwise return the (modified) query data.
Called before each save operation, after validation. Return a non-true result to halt the save.
Called during validation operations, before validation. Please note that custom validation rules can be defined in $validate.
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.
Escapes the field name and prepends the model name. Escaping is done according to the current database driver's rules.
Returns the content of a single field given the supplied conditions, of the first record in the supplied order.
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.
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.
Returns a list of all events that will fire in the model during it's lifecycle. You can override this function to add your own listener callbacks
Marks a field as invalid, optionally setting the name of validation rule (in case of multiple validation for field) that was broken.
Gets the name and fields to be used by a join model. This allows specifying join fields in the association definition.
Returns a list of fields from the database, and sets the current model data (Model::$data) with the record found.
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()
Saves model data (based on white-list, if supplied) to the database. By default, validation occurs before save. Passthrough method to _doSave() with transaction handling.
Backwards compatible passthrough method for: saveMany(), validateMany(), saveAssociated() and validateAssociated()
Saves the value of a single field to the database, based on the current model ID.
Returns an array of table metadata (column names and types) from the database. $field => keys(type, null, default, key, length, extra)
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.
__call( string $method , array $params )
Handles custom method calls, like findBy
$method
$params
__construct( boolean|integer|string|array $id false , string $table null , string $ds null )
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
When overriding Model::__construct() be careful to include and pass in all 3 of the arguments to parent::__construct($id, $table, $ds);
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.
$id
optional false Set this ID for this model on startup, can also be an array of options, see above.
$table
optional null $ds
optional null Object::__construct()
__get( string $name )
Returns the value of the requested variable if it can be set by __isset()
$name
__isset( string $name )
Handles the lazy loading of model associations by looking in the association arrays for the requested variable
$name
_addToWhiteList( string $key , array $options )
Helper method for saveAll() and friends, to add foreign key to fieldlist
$key
$options
_clearCache( string $type null )
Clears cache for this model.
$type
optional null If null this deletes cached views if Cache.check is true Will be used to allow deleting query cache also
_collectForeignKeys( string $type 'belongsTo' )
Collects foreign keys from associations.
$type
optional 'belongsTo' _constructLinkedModel( string $assoc , string $className null , string $plugin null )
Protected helper method to create associated models of a given class.
$assoc
$className
optional null $plugin
optional null name of the plugin where $className is located examples: public $hasMany = array('Assoc' => array('className' => 'ModelName')); usage: $this->Assoc->modelMethods();
public $hasMany = array('ModelName'); usage: $this->ModelName->modelMethods();
_deleteDependent( string $id , boolean $cascade )
Cascades model deletes through associated hasMany and hasOne child records.
$id
$cascade
_deleteLinks( string $id )
Cascades model deletes through HABTM join keys.
$id
_doSave( array $data null , array $options array() )
Saves model data (based on white-list, if supplied) to the database. By default, validation occurs before save.
$data
optional null $options
optional array() can have following keys:
counterCache
: Boolean to control updating of counter caches (if any)_filterResults( array $results , boolean $primary true )
Passes query results through model and behavior afterFind() methods.
$results
$primary
optional true _findAll( string $state , array $query , array $results array() )
Handles the before/after filter logic for find('all') operations. Only called by Model::find().
$state
$query
$results
optional array() _findCount( string $state , array $query , array $results array() )
Handles the before/after filter logic for find('count') operations. Only called by Model::find().
$state
$query
$results
optional array() _findFirst( string $state , array $query , array $results array() )
Handles the before/after filter logic for find('first') operations. Only called by Model::find().
$state
$query
$results
optional array() _findList( string $state , array $query , array $results array() )
Handles the before/after filter logic for find('list') operations. Only called by Model::find().
$state
$query
$results
optional array() _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.
$state
$query
$results
optional array() _findThreaded( string $state , array $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
$state
$query
$results
optional array() _generateAssociation( string $type , string $assocKey )
Build an array-based association from string.
$type
$assocKey
_isUUIDField( string $field )
Check if the passed in field is a UUID field
$field
_normalizeXmlData( array $xml )
Normalize Xml::toArray()
to use in Model::save()
$xml
_prepareUpdateFields( array $data )
Helper method for Model::updateCounterCache()
. Checks the fields to be updated for
$data
Returns updated foreign key values, along with an 'old' key containing the old values, or empty if no foreign keys are updated.
_readDataSource( string $type , array $query )
Read from the datasource
Model::_readDataSource() is used by all find() calls to read from the data source and can be overloaded to allow caching of datasource calls.
protected function _readDataSource($type, $query) { $cacheName = md5(json_encode($query) . json_encode($this->hasOne) . json_encode($this->belongsTo)); $cache = Cache::read($cacheName, 'cache-config-name'); if ($cache !== false) { return $cache; } $results = parent::_readDataSource($type, $query); Cache::write($cacheName, $results, 'cache-config-name'); return $results; }
$type
$query
_saveMulti( array $joined , integer|string $id , DataSource $db )
Saves model hasAndBelongsToMany data to the database.
$joined
$id
DataSource
$db
_setAliasData( array $data )
Move values to alias
$data
afterDelete( )
Called after every deletion operation.
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.
$results
$primary
optional false afterSave( boolean $created , array $options array() )
Called after each successful save operation.
$created
$options
optional array() beforeDelete( boolean $cascade true )
Called before every deletion operation.
$cascade
optional true beforeFind( array $query )
Called before each find operation. Return false if you want to halt the find call, otherwise return the (modified) query data.
$query
true if the operation should continue, false if it should abort; or, modified $query to continue with new $query
beforeSave( array $options array() )
Called before each save operation, after validation. Return a non-true result to halt the save.
$options
optional array() beforeValidate( array $options array() )
Called during validation operations, before validation. Please note that custom validation rules can be defined in $validate.
$options
optional array() bindModel( array $params , boolean $reset true )
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.
$params
$reset
optional true 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.
$type
optional 'first' $query
optional array() clear( )
This function is a convenient wrapper class to create(false) and, as the name suggests, clears the id, data, and validation errors.
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.
$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.
$filterKey
optional false deconstruct( string $field , array|object $data )
Deconstructs a complex data type (array or object) into a single field value.
$field
$data
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.
$id
optional null $cascade
optional true deleteAll( mixed $conditions , boolean $cascade true , boolean $callbacks false )
Deletes multiple model records based on a set of conditions.
$conditions
$cascade
optional true $callbacks
optional false 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.
$field
optional null $alias
optional null Post
.id
).exists( integer|string $id null )
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.
$id
optional null field( string $name , array $conditions null , string $order null )
Returns the content of a single field given the supplied conditions, of the first record in the supplied order.
$name
$conditions
optional null $order
optional null find( string $type 'first' , array $query array() )
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' => 1, '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`' ) ) ));
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.
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':
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.
$type
optional 'first' $query
optional array() getAffectedRows( )
Returns the number of rows affected by the last query.
getAssociated( string $type null )
Gets all the models with which this model is associated.
$type
optional null getColumnType( string $column )
Returns the column type of a column in the model.
$column
getColumnTypes( )
Returns an associative array of field names and column types.
getDataSource( )
Gets the DataSource to which this model is bound.
DataSource
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.
CakeEventManager
getID( integer $list 0 )
Returns the current record's ID
$list
optional 0 getInsertID( )
Returns the ID of the last record this model inserted.
getLastInsertID( )
Returns the ID of the last record this model inserted.
getNumRows( )
Returns the number of rows returned from the last query.
getVirtualField( string $field null )
Returns the expression for a model virtual field
$field
optional null 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( array $conditions null )
Returns true if a record that meets given conditions exists.
$conditions
optional null hasField( string|array $name , boolean $checkVirtual false )
Returns true if the supplied field exists in the model's database table.
$name
$checkVirtual
optional false 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( 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.
$method
implementedEvents( )
Returns a list of all events that will fire in the model during it's lifecycle. You can override this function to add your own listener callbacks
CakeEventListener::implementedEvents()
invalidFields( array|string $options array() )
Returns an array of fields that have failed the validation of the current model.
Additionally it populates the validationErrors property of the model with the same array.
$options
optional array() 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.
$field
$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( string $field )
Returns true if given field name is a foreign key in this model.
$field
isUnique( array $fields , boolean|array $or true )
Returns false if any fields passed match any (by default, all if $or = false) of their matching values.
Can be used as a validation method. When used as a validation method, the $or
parameter contains an array of fields to be validated.
$fields
$or
optional true isVirtualField( string $field )
Returns true if the supplied field is a model Virtual Field
$field
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.
$assoc
$keys
optional array() onError( )
Called when a DataSource-level error occurs.
query( string $sql )
Returns a resultset for a given SQL statement. Custom SQL queries should be performed with this method.
The method can options 2nd and 3rd parameters.
$sql
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.
$fields
optional null $id
optional null 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()
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. Passthrough method to _doSave() with transaction handling.
$data
optional null $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:
counterCache
: Boolean to control updating of counter caches (if any)$fieldList
optional array() saveAll( array $data array() , array $options array() )
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.
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/saveAssociatedcallbacks
: See Model::save()counterCache
: See Model::save()$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.
$options
optional 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 saved successfully.
saveAssociated( array $data null , array $options array() )
Saves a single record, as well as all its directly associated records.
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.callbacks
: See Model::save()counterCache
: See Model::save()$data
optional null $options
optional 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 saved successfully.
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.
$name
$value
$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', 'callbacks' and 'counterCache' options. See Model::save() for details of each options.
saveMany( array $data null , array $options array() )
Saves multiple individual records for a single model
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.callbacks
: See Model::save()counterCache
: See Model::save()$data
optional null $options
optional 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 saved successfully.
schema( boolean|string $field false )
Returns an array of table metadata (column names and types) from the database. $field => keys(type, null, default, key, length, extra)
$field
optional false set( string|array|SimpleXmlElement|DomNode $one , string $two null )
This function does two things:
$one
$two
optional null setDataSource( string $dataSource null )
Sets the DataSource to which this model is bound.
$dataSource
optional null MissingConnectionException
setInsertID( integer|string $id )
Sets the ID of the last record this model inserted
$id
setSource( string $tableName )
Sets a custom table for your model class. Used by your controller to select a database table.
$tableName
MissingTableException
unbindModel( array $params , boolean $reset true )
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')));
Or alternatively: $this->User->unbindModel(array('hasMany' => 'SupportRequest'));
Unbound models that are not made permanent will reset with the next call to Model::find()
$params
$reset
optional true updateAll( array $fields , mixed $conditions true )
Updates multiple model records based on a set of conditions.
$fields
Set of fields and values, indexed by fields. Fields are treated as SQL snippets, to insert literal values manually escape your data.
$conditions
optional true updateCounterCache( array $keys array() , boolean $created false )
Updates the counter cache of belongsTo associations after a save or delete operation
$keys
optional array() $created
optional false True if a new record was created, otherwise only associations with 'counterScope' defined get updated
validateAssociated( array $data , array $options array() )
Validates a single record, as well as all its directly associated records.
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
$data
$options
optional 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.
validateMany( array $data , array $options array() )
Validates multiple individual records for a single model
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
$data
$options
optional 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( 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.
Will validate the currently set data. Use Model::set() or Model::create() to set the active data.
$options
optional array() validator( ModelValidator $instance null )
Returns an instance of a model validator for this class
ModelValidator
$instance
optional null Model validator instance. If null a new ModelValidator instance will be made using current model object
ModelValidator
_mergeVars( array $properties , string $class , boolean $normalize true )
Merges this objects $property with the property in $class' definition. This classes value for the property will be merged on top of $class'
This provides some of the DRY magic CakePHP provides. If you want to shut it off, redefine this method as an empty function.
$properties
$class
$normalize
optional true _set( array $properties array() )
Allows setting of multiple properties of the object in a single line of code. Will only set properties that are part of a class declaration.
$properties
optional array() _stop( integer|string $status 0 )
Stop execution of the current script. Wraps exit() making testing easier.
$status
optional 0 dispatchMethod( string $method , array $params array() )
Calls a method on this object with the given parameters. Provides an OO wrapper for call_user_func_array
$method
$params
optional array() log( string $msg , integer $type LOG_ERR , null|string|array $scope null )
Convenience method to write a message to CakeLog. See CakeLog::write() for more information on writing to logs.
$msg
$type
optional LOG_ERR $scope
optional null The scope(s) a log message is being created in. See CakeLog::config() for more information on logging scopes.
requestAction( string|array $url , array $extra array() )
Calls a controller's method from any location. Can be used to connect controllers together or tie plugins into a main application. requestAction can be used to return rendered views or fetch the return value from controller actions.
Under the hood this method uses Router::reverse() to convert the $url parameter into a string URL. You should use URL formats that are compatible with Router::reverse()
POST and GET data can be simulated in requestAction. Use $extra['url']
for GET data. The $extra['data']
parameter allows POST data simulation.
$url
String or array-based URL. Unlike other URL arrays in CakePHP, this URL will not automatically handle passed and named arguments in the $url parameter.
$extra
optional array() if array includes the key "return" it sets the AutoRender to true. Can also be used to submit GET/POST data, and named/passed arguments.
Boolean true or false on success/failure, or contents of rendered action if 'return' is set in $extra.
toString( )
Object-to-string conversion. Each class can override this method as necessary.
public BehaviorCollection
Holds the Behavior objects currently bound to this model.
null
public array
Holds model associations temporarily to allow for dynamic (un)binding.
array()
public boolean
Safe update mode If true, this prevents Model::save() from generating a query with WHERE 1 = 1 on race condition.
false
protected array
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') )
protected array
Holds provided/generated association key names and other data for all associations.
array('belongsTo', 'hasOne', 'hasMany', 'hasAndBelongsToMany')
protected CakeEventManager
Instance of the CakeEventManager this model is using to dispatch inner events.
null
protected boolean
Has the datasource been configured.
false
public array
List of behaviors to load when the model object is initialized. Settings can be passed to behaviors by using the behavior name as index.
For example:
public $actsAs = array( 'Translate', 'MyBehavior' => array('setting1' => 'value1') );
null
public array
Detailed list of belongsTo associations.
public $belongsTo = array('Group', 'Department');
public $belongsTo = array( 'Group', 'Department' => array( 'className' => 'Department', 'foreignKey' => 'department_id' ) );
className
: the class name 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.array()
public boolean
Whether or not to cache queries for this model. This enables in-memory caching only, the results are not stored beyond the current request.
false
public array
Container for the data that this model gets from persistent storage (usually, a database).
array()
public string
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
null
public array
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 array
Detailed list of hasAndBelongsToMany associations.
public $hasAndBelongsToMany = array('Role', 'Address');
public $hasAndBelongsToMany = array( 'Role', 'Address' => array( 'className' => 'Address', 'foreignKey' => 'user_id', 'associationForeignKey' => 'address_id', 'joinTable' => 'addresses_users' ) );
className
: the class name 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
, A complete SQL query CakePHP can use to fetch associated model records. This should be used in situations that require very custom results.array()
public array
Detailed list of hasMany associations.
public $hasMany = array('Comment', 'Task');
public $hasMany = array( 'Comment', 'Task' => array( 'className' => 'Task', 'foreignKey' => 'user_id' ) );
className
: the class name 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.array()
public array
Detailed list of hasOne associations.
public $hasOne = array('Profile', 'Address');
public $hasOne = array( 'Profile', 'Address' => array( 'className' => 'Address', 'foreignKey' => 'user_id' ) );
className
: the class name 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.array()
public mixed
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 of the model.
null
public string
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");
null
public string
The name of the primary key field for this model.
null
public integer
Number of associations to recurse through during find calls. Fetches only the first level by default.
1
public string
Holds physical schema/database name for this model. Automatically set during Model creation.
null
public string
Database table prefix for tables in model.
null
public array
List of table names included in the model description. Used for associations.
array()
public boolean
If true, afterFind will be passed consistent formatted $results in case of $primary is false. The format will be such as the following.
$results = array( 0 => array( 'ModelName' => array( 'field1' => 'value1', 'field2' => 'value2' ) ) );
true
public string
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()
.
'default'
public string
Custom database table name, or null/false if no table association is desired.
null
public array
List of validation rules. It must be an array with the field name as key and using as value one of the following possibilities
public $validate = array( 'name' => '/^[a-z].+$/i' );
public $validate = array( 'name' => 'notBlank' );
public $validate = array( 'length' => array( 'rule' => array('lengthBetween', 5, 25) ) );
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; }
The messages will be used in Model::$validationErrors and can be used in the FormHelper
public $validate = array( 'length' => array( 'rule' => array('lengthBetween', 5, 15), 'message' => array('Between %d to %d characters') ) );
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') ) ) );
rule
: String with method name, regular expression (started by slash) or array with method and parametersmessage
: String with the message or array if have multiple parameters. See http://php.net/sprintflast
: 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 saveallowEmpty
: Boolean value to indicate if the field can be emptyon
: Possible values: update
, create
. Indicate to apply this rule only on update or createarray()
public string
Name of the validation string domain to use when translating validation errors.
null
public array
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
array()
© 2005–2016 The Cake Software Foundation, Inc.
Licensed under the MIT License.
CakePHP is a registered trademark of Cake Software Foundation, Inc.
We are not endorsed by or affiliated with CakePHP.
http://api.cakephp.org/2.8/class-Model.html