2008-05-30 11:40:08 +00:00
< ? php
/**
* Object - relational mapper .
*
2013-10-09 23:38:16 +00:00
* DBO - backed object data model , for mapping database tables to CakePHP objects .
2008-05-30 11:40:08 +00:00
*
2009-05-01 21:05:46 +00:00
* CakePHP ( tm ) : Rapid Development Framework ( http :// cakephp . org )
2013-02-08 11:59:49 +00:00
* Copyright ( c ) Cake Software Foundation , Inc . ( http :// cakefoundation . org )
2008-05-30 11:40:08 +00:00
*
* Licensed under The MIT License
2013-02-08 12:22:51 +00:00
* For full copyright and license information , please see the LICENSE . txt
2008-05-30 11:40:08 +00:00
* Redistributions of files must retain the above copyright notice .
*
2013-02-08 11:59:49 +00:00
* @ copyright Copyright ( c ) Cake Software Foundation , Inc . ( http :// cakefoundation . org )
2010-01-26 19:18:20 +00:00
* @ link http :// cakephp . org CakePHP ( tm ) Project
2011-07-26 06:16:14 +00:00
* @ package Cake . Model
2008-10-30 17:30:26 +00:00
* @ since CakePHP ( tm ) v 0.10 . 0.0
2013-05-30 22:11:14 +00:00
* @ license http :// www . opensource . org / licenses / mit - license . php MIT License
2008-05-30 11:40:08 +00:00
*/
2009-07-24 19:18:37 +00:00
2010-12-07 06:14:17 +00:00
App :: uses ( 'ClassRegistry' , 'Utility' );
App :: uses ( 'Validation' , 'Utility' );
App :: uses ( 'String' , 'Utility' );
2012-03-14 02:06:20 +00:00
App :: uses ( 'Hash' , 'Utility' );
2010-12-03 23:07:21 +00:00
App :: uses ( 'BehaviorCollection' , 'Model' );
App :: uses ( 'ModelBehavior' , 'Model' );
2012-03-22 11:18:57 +00:00
App :: uses ( 'ModelValidator' , 'Model' );
2010-12-03 23:07:21 +00:00
App :: uses ( 'ConnectionManager' , 'Model' );
2010-12-07 06:14:17 +00:00
App :: uses ( 'Xml' , 'Utility' );
2011-12-26 17:36:48 +00:00
App :: uses ( 'CakeEvent' , 'Event' );
App :: uses ( 'CakeEventListener' , 'Event' );
App :: uses ( 'CakeEventManager' , 'Event' );
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* 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 ' )
2008-10-31 19:05:30 +00:00
* The table is required to have at least 'id auto_increment' primary key .
2008-05-30 11:40:08 +00:00
*
2011-07-26 06:16:14 +00:00
* @ package Cake . Model
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models . html
2008-05-30 11:40:08 +00:00
*/
2011-12-26 17:36:48 +00:00
class Model extends Object implements CakeEventListener {
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* The name of the DataSource connection that this Model uses
*
2011-08-15 04:17:40 +00:00
* The value must be an attribute name that you defined in `app/Config/database.php`
* or created using `ConnectionManager::create()` .
*
2008-05-30 11:40:08 +00:00
* @ var string
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #usedbconfig
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $useDbConfig = 'default' ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Custom database table name , or null / false if no table association is desired .
2008-05-30 11:40:08 +00:00
*
* @ var string
2012-05-05 23:21:20 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #usetable
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $useTable = null ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* Custom display field name . Display fields are used by Scaffold , in SELECT boxes ' OPTION elements .
*
2011-08-15 04:35:20 +00:00
* This field is also used in `find('list')` when called with no extra parameters in the fields list
2011-08-15 04:17:40 +00:00
*
2008-05-30 11:40:08 +00:00
* @ var string
2012-05-05 23:21:20 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #displayfield
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $displayField = null ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-11-08 02:54:07 +00:00
* Value of the primary key ID of the record that this model is currently pointing to .
2008-10-31 19:05:30 +00:00
* Automatically set after database insertions .
2008-05-30 11:40:08 +00:00
*
* @ var mixed
*/
2010-04-04 07:14:00 +00:00
public $id = false ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Container for the data that this model gets from persistent storage ( usually , a database ) .
2008-05-30 11:40:08 +00:00
*
* @ var array
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #data
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $data = array ();
2009-07-24 19:18:37 +00:00
2011-11-05 10:57:08 +00:00
/**
2012-12-22 22:48:15 +00:00
* Holds physical schema / database name for this model . Automatically set during Model creation .
2011-11-05 10:57:08 +00:00
*
* @ var string
*/
public $schemaName = null ;
2008-05-30 11:40:08 +00:00
/**
* Table name for this Model .
*
* @ var string
*/
2010-04-04 07:14:00 +00:00
public $table = false ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* The name of the primary key field for this model .
2008-05-30 11:40:08 +00:00
*
* @ var string
2014-07-10 09:46:48 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #primarykey
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $primaryKey = null ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Field - by - field table metadata .
2008-05-30 11:40:08 +00:00
*
* @ var array
*/
2010-04-04 06:36:12 +00:00
protected $_schema = null ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2011-08-15 04:35:20 +00:00
* List of validation rules . It must be an array with the field name as key and using
* as value one of the following possibilities
2011-08-15 04:17:40 +00:00
*
* ### Validating using regular expressions
*
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
* public $validate = array (
* 'name' => '/^[a-z].+$/i'
* );
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
*
* ### Validating using methods (no parameters)
*
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
* public $validate = array (
* 'name' => 'notEmpty'
* );
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
*
* ### Validating using methods (with parameters)
*
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
* public $validate = array (
2014-05-13 07:31:03 +00:00
* 'length' => array (
* 'rule' => array ( 'lengthBetween' , 5 , 25 )
2011-08-15 04:17:40 +00:00
* )
* );
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
*
* ### Validating using custom method
*
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
* 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 ;
* }
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
*
* ### Validations with messages
*
* The messages will be used in Model :: $validationErrors and can be used in the FormHelper
*
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
* public $validate = array (
2014-05-13 07:31:03 +00:00
* 'length' => array (
* 'rule' => array ( 'lengthBetween' , 5 , 15 ),
* 'message' => array ( 'Between %d to %d characters' )
2011-08-15 04:17:40 +00:00
* )
* );
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
*
* ### Multiple validations to the same field
*
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
* public $validate = array (
* 'login' => array (
* array (
2011-10-06 02:02:15 +00:00
* 'rule' => 'alphaNumeric' ,
2011-08-15 04:17:40 +00:00
* 'message' => 'Only alphabets and numbers allowed' ,
* 'last' => true
* ),
* array (
2011-10-06 02:02:15 +00:00
* 'rule' => array ( 'minLength' , 8 ),
2011-08-15 04:17:40 +00:00
* 'message' => array ( 'Minimum length of %d characters' )
* )
* )
* );
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 04:17:40 +00:00
*
* ### Valid keys in validations
*
2011-10-06 02:03:18 +00:00
* - `rule` : String with method name , regular expression ( started by slash ) or array with method and parameters
2011-08-15 04:17:40 +00:00
* - `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
2008-05-30 11:40:08 +00:00
*
* @ var array
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #validate
* @ link http :// book . cakephp . org / 2.0 / en / models / data - validation . html
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $validate = array ();
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* List of validation errors .
2008-05-30 11:40:08 +00:00
*
* @ var array
*/
2010-04-04 07:14:00 +00:00
public $validationErrors = array ();
2009-07-24 19:18:37 +00:00
2011-06-20 05:06:31 +00:00
/**
2011-07-07 12:14:06 +00:00
* Name of the validation string domain to use when translating validation errors .
2011-06-20 05:06:31 +00:00
*
* @ var string
*/
public $validationDomain = null ;
2008-05-30 11:40:08 +00:00
/**
* Database table prefix for tables in model .
*
* @ var string
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #tableprefix
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $tablePrefix = null ;
2009-07-24 19:18:37 +00:00
2012-06-19 21:46:34 +00:00
/**
* Plugin model belongs to .
*
* @ var string
*/
public $plugin = null ;
2008-05-30 11:40:08 +00:00
/**
* Name of the model .
*
* @ var string
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #name
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $name = null ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* Alias name for model .
*
* @ var string
*/
2010-04-04 07:14:00 +00:00
public $alias = null ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* List of table names included in the model description . Used for associations .
2008-05-30 11:40:08 +00:00
*
* @ var array
*/
2010-04-04 07:14:00 +00:00
public $tableToModel = array ();
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2012-12-22 22:48:15 +00:00
* Whether or not to cache queries for this model . This enables in - memory
2008-10-31 19:05:30 +00:00
* caching only , the results are not stored beyond the current request .
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ var bool
2012-05-05 23:21:20 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #cachequeries
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $cacheQueries = false ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Detailed list of belongsTo associations .
2008-05-30 11:40:08 +00:00
*
2011-08-15 05:10:32 +00:00
* ### Basic usage
*
* `public $belongsTo = array('Group', 'Department');`
*
* ### Detailed configuration
*
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 05:10:32 +00:00
* public $belongsTo = array (
* 'Group' ,
* 'Department' => array (
* 'className' => 'Department' ,
* 'foreignKey' => 'department_id'
* )
* );
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 05:10:32 +00:00
*
* ### Possible keys in association
*
2013-10-23 02:59:50 +00:00
* - `className` : the class name of the model being associated to the current model .
2012-01-11 18:37:52 +00:00
* If you 're defining a ' Profile belongsTo User ' relationship, the className key should equal ' User . '
2011-08-15 05:10:32 +00:00
* - `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
2012-01-11 18:37:52 +00:00
* 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.'
2011-08-15 05:10:32 +00:00
* - `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
2012-01-11 18:37:52 +00:00
* decrease the " [singular_model_name]_count " field in the foreign table whenever you do
2011-08-15 05:10:32 +00:00
* 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 .
*
2008-05-30 11:40:08 +00:00
* @ var array
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / associations - linking - models - together . html #belongsto
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $belongsTo = array ();
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Detailed list of hasOne associations .
2008-05-30 11:40:08 +00:00
*
2011-08-15 05:10:32 +00:00
* ### Basic usage
*
* `public $hasOne = array('Profile', 'Address');`
*
* ### Detailed configuration
*
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 05:10:32 +00:00
* public $hasOne = array (
* 'Profile' ,
* 'Address' => array (
* 'className' => 'Address' ,
* 'foreignKey' => 'user_id'
* )
* );
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 05:10:32 +00:00
*
* ### Possible keys in association
*
2013-10-23 02:59:50 +00:00
* - `className` : the class name of the model being associated to the current model .
2012-01-11 18:37:52 +00:00
* If you 're defining a ' User hasOne Profile ' relationship, the className key should equal ' Profile . '
2011-08-15 05:10:32 +00:00
* - `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
2012-01-11 18:37:52 +00:00
* 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. "
2011-08-15 05:10:32 +00:00
* - `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 .
2012-01-11 18:37:52 +00:00
* - `dependent` : When the dependent key is set to true , and the model ' s delete ()
2011-08-15 05:10:32 +00:00
* 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 .
*
2008-05-30 11:40:08 +00:00
* @ var array
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / associations - linking - models - together . html #hasone
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $hasOne = array ();
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Detailed list of hasMany associations .
2008-05-30 11:40:08 +00:00
*
2011-08-15 05:10:32 +00:00
* ### Basic usage
*
* `public $hasMany = array('Comment', 'Task');`
*
* ### Detailed configuration
*
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 05:10:32 +00:00
* public $hasMany = array (
* 'Comment' ,
* 'Task' => array (
* 'className' => 'Task' ,
* 'foreignKey' => 'user_id'
* )
* );
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 05:10:32 +00:00
*
* ### Possible keys in association
*
2013-10-23 02:59:50 +00:00
* - `className` : the class name of the model being associated to the current model .
2012-01-11 18:37:52 +00:00
* If you 're defining a ' User hasMany Comment ' relationship, the className key should equal ' Comment . '
2011-08-15 05:10:32 +00:00
* - `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
2012-01-11 18:37:52 +00:00
* 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. "
2011-08-15 05:10:32 +00:00
* - `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 .
*
2008-05-30 11:40:08 +00:00
* @ var array
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / associations - linking - models - together . html #hasmany
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $hasMany = array ();
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Detailed list of hasAndBelongsToMany associations .
2008-05-30 11:40:08 +00:00
*
2011-08-15 05:10:32 +00:00
* ### Basic usage
*
* `public $hasAndBelongsToMany = array('Role', 'Address');`
*
* ### Detailed configuration
*
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 05:10:32 +00:00
* public $hasAndBelongsToMany = array (
* 'Role' ,
* 'Address' => array (
* 'className' => 'Address' ,
* 'foreignKey' => 'user_id' ,
* 'associationForeignKey' => 'address_id' ,
* 'joinTable' => 'addresses_users'
* )
* );
2015-01-09 12:47:25 +00:00
* `` `
2011-08-15 05:10:32 +00:00
*
* ### Possible keys in association
*
2013-10-23 02:59:50 +00:00
* - `className` : the class name of the model being associated to the current model .
2012-01-11 18:37:52 +00:00
* If you 're defining a ' Recipe HABTM Tag ' relationship, the className key should equal ' Tag . '
2011-08-15 05:10:32 +00:00
* - `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
2012-01-11 18:37:52 +00:00
* current model , suffixed with '_id' .
2011-08-15 05:10:32 +00:00
* - `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
2012-01-11 18:37:52 +00:00
* model , suffixed with '_id' .
2011-08-15 05:10:32 +00:00
* - `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 .
2012-01-17 21:02:30 +00:00
* To prevent deletion of existing relationship records , set this key to a string 'keepExisting' .
2011-08-15 05:10:32 +00:00
* - `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 .
2013-08-19 01:37:37 +00:00
* - `finderQuery` , A complete SQL query CakePHP
* can use to fetch associated model records . This should
2011-08-15 05:10:32 +00:00
* be used in situations that require very custom results .
*
2008-05-30 11:40:08 +00:00
* @ var array
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / associations - linking - models - together . html #hasandbelongstomany-habtm
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $hasAndBelongsToMany = array ();
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* 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 :
*
2010-04-04 07:14:00 +00:00
* public $actsAs = array ( 'Translate' , 'MyBehavior' => array ( 'setting1' => 'value1' ))
2008-05-30 11:40:08 +00:00
*
* @ var array
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / behaviors . html #using-behaviors
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $actsAs = null ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Holds the Behavior objects currently bound to this model .
2008-05-30 11:40:08 +00:00
*
2009-03-17 21:10:28 +00:00
* @ var BehaviorCollection
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $Behaviors = null ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Whitelist of fields allowed to be saved .
2008-05-30 11:40:08 +00:00
*
* @ var array
*/
2010-04-04 07:14:00 +00:00
public $whitelist = array ();
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Whether or not to cache sources for this model .
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ var bool
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $cacheSources = true ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Type of find query currently executing .
2008-05-30 11:40:08 +00:00
*
* @ var string
*/
2010-04-04 07:14:00 +00:00
public $findQueryType = null ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-11-08 02:54:07 +00:00
* Number of associations to recurse through during find calls . Fetches only
2008-10-31 19:05:30 +00:00
* the first level by default .
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ var int
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #recursive
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $recursive = 1 ;
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-11-08 02:54:07 +00:00
* The column name ( s ) and direction ( s ) to order find results by default .
*
2010-04-04 07:14:00 +00:00
* public $order = " Post.created DESC " ;
* public $order = array ( " Post.view_count DESC " , " Post.rating DESC " );
2008-05-30 11:40:08 +00:00
*
* @ var string
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #order
2008-05-30 11:40:08 +00:00
*/
2010-04-04 07:14:00 +00:00
public $order = null ;
2009-07-24 19:18:37 +00:00
2009-12-20 21:26:12 +00:00
/**
2012-12-22 22:48:15 +00:00
* Array of virtual fields this model has . Virtual fields are aliased
2009-12-20 21:26:12 +00:00
* SQL expressions . Fields added to this property will be read as other fields in a model
* but will not be saveable .
*
2010-04-04 07:14:00 +00:00
* `public $virtualFields = array('two' => '1 + 1');`
2009-12-20 21:26:12 +00:00
*
* Is a simplistic example of how to set virtualFields
*
* @ var array
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / model - attributes . html #virtualfields
2009-12-20 21:26:12 +00:00
*/
2010-04-04 07:14:00 +00:00
public $virtualFields = array ();
2009-12-20 21:26:12 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Default list of association keys .
2008-05-30 11:40:08 +00:00
*
* @ var array
*/
2011-08-20 04:43:34 +00:00
protected $_associationKeys = array (
2009-03-08 18:05:18 +00:00
'belongsTo' => array ( 'className' , 'foreignKey' , 'conditions' , 'fields' , 'order' , 'counterCache' ),
2011-12-01 07:21:31 +00:00
'hasOne' => array ( 'className' , 'foreignKey' , 'conditions' , 'fields' , 'order' , 'dependent' ),
2009-03-08 18:05:18 +00:00
'hasMany' => array ( 'className' , 'foreignKey' , 'conditions' , 'fields' , 'order' , 'limit' , 'offset' , 'dependent' , 'exclusive' , 'finderQuery' , 'counterQuery' ),
2013-08-19 01:37:37 +00:00
'hasAndBelongsToMany' => array ( 'className' , 'joinTable' , 'with' , 'foreignKey' , 'associationForeignKey' , 'conditions' , 'fields' , 'order' , 'limit' , 'offset' , 'unique' , 'finderQuery' )
2009-03-08 18:05:18 +00:00
);
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Holds provided / generated association key names and other data for all associations .
2008-05-30 11:40:08 +00:00
*
* @ var array
*/
2011-08-20 04:43:34 +00:00
protected $_associations = array ( 'belongsTo' , 'hasOne' , 'hasMany' , 'hasAndBelongsToMany' );
2009-07-24 19:18:37 +00:00
2012-11-04 11:23:36 +00:00
// @codingStandardsIgnoreStart
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Holds model associations temporarily to allow for dynamic ( un ) binding .
2008-05-30 11:40:08 +00:00
*
* @ var array
*/
2010-12-12 20:48:36 +00:00
public $__backAssociation = array ();
2011-07-31 21:05:20 +00:00
/**
* Back inner association
*
* @ var array
*/
2010-12-12 20:48:36 +00:00
public $__backInnerAssociation = array ();
2011-01-29 22:43:01 +00:00
2011-07-31 21:05:20 +00:00
/**
* Back original association
*
* @ var array
*/
2010-12-12 20:48:36 +00:00
public $__backOriginalAssociation = array ();
2011-01-29 22:43:01 +00:00
2011-07-31 21:05:20 +00:00
/**
* Back containable association
*
* @ var array
*/
2010-12-12 20:48:36 +00:00
public $__backContainableAssociation = array ();
2009-07-24 19:18:37 +00:00
2014-07-12 02:56:36 +00:00
/**
* Safe update mode
* If true , this prevents Model :: save () from generating a query with WHERE 1 = 1 on race condition .
*
* @ var bool
*/
public $__safeUpdateMode = false ;
2012-11-04 11:23:36 +00:00
// @codingStandardsIgnoreEnd
2014-08-10 15:21:51 +00:00
/**
* If true , afterFind will be passed consistent formatted $results in case of $primary is false .
* The format will be such as the following .
*
2015-01-09 12:47:25 +00:00
* `` `
2014-08-10 15:21:51 +00:00
* $results = array (
* 0 => array (
* 'ModelName' => array (
* 'field1' => 'value1' ,
* 'field2' => 'value2'
* )
* )
* );
2015-01-09 12:47:25 +00:00
* `` `
2014-08-10 15:21:51 +00:00
*
* @ var bool
*/
public $useConsistentAfterFind = true ;
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* The ID of the model record that was last inserted .
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ var int
2008-05-30 11:40:08 +00:00
*/
2011-08-20 04:43:34 +00:00
protected $_insertID = null ;
2009-07-24 19:18:37 +00:00
2011-02-12 03:39:09 +00:00
/**
* Has the datasource been configured .
*
2014-07-03 13:36:42 +00:00
* @ var bool
2011-02-12 03:39:09 +00:00
* @ see Model :: getDataSource
*/
2011-08-20 04:43:34 +00:00
protected $_sourceConfigured = false ;
2011-02-12 03:39:09 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* List of valid finder method options , supplied as the first parameter to find () .
2008-05-30 11:40:08 +00:00
*
* @ var array
*/
2011-04-17 00:39:00 +00:00
public $findMethods = array (
2008-09-21 04:09:16 +00:00
'all' => true , 'first' => true , 'count' => true ,
'neighbors' => true , 'list' => true , 'threaded' => true
);
2009-07-24 19:18:37 +00:00
2011-12-26 17:36:48 +00:00
/**
* Instance of the CakeEventManager this model is using
* to dispatch inner events .
*
* @ var CakeEventManager
*/
protected $_eventManager = null ;
2012-03-22 11:18:57 +00:00
/**
* Instance of the ModelValidator
*
* @ var ModelValidator
*/
protected $_validator = null ;
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Constructor . Binds the model ' s database table to the object .
2008-05-30 11:40:08 +00:00
*
2010-01-02 04:58:07 +00:00
* If `$id` is an array it can be used to pass several options into the model .
*
2013-04-07 18:56:59 +00:00
* - `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` .
2010-01-02 04:58:07 +00:00
* eg . `ParentThread`
*
* ### Overriding Model's __construct method.
2010-01-14 17:57:43 +00:00
*
* When overriding Model :: __construct () be careful to include and pass in all 3 of the
2010-01-02 04:58:07 +00:00
* arguments to `parent::__construct($id, $table, $ds);`
*
* ### Dynamically creating models
*
2010-07-19 22:29:18 +00:00
* You can dynamically create model instances using the $id array syntax .
2010-01-14 17:57:43 +00:00
*
2015-01-09 12:47:25 +00:00
* `` `
2010-01-02 04:58:07 +00:00
* $Post = new Model ( array ( 'table' => 'posts' , 'name' => 'Post' , 'ds' => 'connection2' ));
2015-01-09 12:47:25 +00:00
* `` `
2010-01-02 04:58:07 +00:00
*
2012-12-22 22:48:15 +00:00
* Would create a model attached to the posts table on connection2 . Dynamic model creation is useful
2010-01-02 04:58:07 +00:00
* when you want a model object that contains no associations or attached behaviors .
*
2014-07-03 13:36:42 +00:00
* @ param bool | int | string | array $id Set this ID for this model on startup ,
2013-10-24 11:05:32 +00:00
* can also be an array of options , see above .
2008-05-30 11:40:08 +00:00
* @ param string $table Name of database table to use .
2010-01-02 04:58:07 +00:00
* @ param string $ds DataSource connection name .
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function __construct ( $id = false , $table = null , $ds = null ) {
2008-05-30 11:40:08 +00:00
parent :: __construct ();
if ( is_array ( $id )) {
2008-08-25 22:33:36 +00:00
extract ( array_merge (
2008-09-21 04:09:16 +00:00
array (
'id' => $this -> id , 'table' => $this -> useTable , 'ds' => $this -> useDbConfig ,
2012-06-19 21:46:34 +00:00
'name' => $this -> name , 'alias' => $this -> alias , 'plugin' => $this -> plugin
2008-09-21 04:09:16 +00:00
),
$id
));
2008-05-30 11:40:08 +00:00
}
2012-06-19 21:46:34 +00:00
if ( $this -> plugin === null ) {
$this -> plugin = ( isset ( $plugin ) ? $plugin : $this -> plugin );
}
2008-05-30 11:40:08 +00:00
if ( $this -> name === null ) {
2008-09-21 04:09:16 +00:00
$this -> name = ( isset ( $name ) ? $name : get_class ( $this ));
2008-05-30 11:40:08 +00:00
}
if ( $this -> alias === null ) {
2008-09-21 04:09:16 +00:00
$this -> alias = ( isset ( $alias ) ? $alias : $this -> name );
2008-05-30 11:40:08 +00:00
}
if ( $this -> primaryKey === null ) {
$this -> primaryKey = 'id' ;
}
2008-09-26 15:27:36 +00:00
2008-05-30 11:40:08 +00:00
ClassRegistry :: addObject ( $this -> alias , $this );
$this -> id = $id ;
unset ( $id );
if ( $table === false ) {
$this -> useTable = false ;
} elseif ( $table ) {
$this -> useTable = $table ;
}
2009-07-24 19:18:37 +00:00
2009-06-16 21:35:21 +00:00
if ( $ds !== null ) {
$this -> useDbConfig = $ds ;
}
2008-05-30 11:40:08 +00:00
2008-09-21 04:09:16 +00:00
if ( is_subclass_of ( $this , 'AppModel' )) {
2011-12-18 15:37:16 +00:00
$merge = array ( 'actsAs' , 'findMethods' );
2008-11-14 20:24:27 +00:00
$parentClass = get_parent_class ( $this );
2010-11-20 05:20:54 +00:00
if ( $parentClass !== 'AppModel' ) {
$this -> _mergeVars ( $merge , $parentClass );
2008-09-21 04:09:16 +00:00
}
2010-11-20 05:20:54 +00:00
$this -> _mergeVars ( $merge , 'AppModel' );
2008-09-21 04:09:16 +00:00
}
2012-03-03 22:45:45 +00:00
$this -> _mergeVars ( array ( 'findMethods' ), 'Model' );
2008-09-21 04:09:16 +00:00
$this -> Behaviors = new BehaviorCollection ();
2008-05-30 11:40:08 +00:00
if ( $this -> useTable !== false ) {
2011-02-23 04:19:02 +00:00
2008-05-30 11:40:08 +00:00
if ( $this -> useTable === null ) {
$this -> useTable = Inflector :: tableize ( $this -> name );
}
2012-09-14 17:26:30 +00:00
if ( ! $this -> displayField ) {
2010-07-16 01:48:16 +00:00
unset ( $this -> displayField );
2008-05-30 11:40:08 +00:00
}
2011-02-23 04:19:02 +00:00
$this -> table = $this -> useTable ;
$this -> tableToModel [ $this -> table ] = $this -> alias ;
2008-10-15 17:30:08 +00:00
} elseif ( $this -> table === false ) {
$this -> table = Inflector :: tableize ( $this -> name );
2008-05-30 11:40:08 +00:00
}
2011-12-08 04:40:22 +00:00
if ( $this -> tablePrefix === null ) {
unset ( $this -> tablePrefix );
}
2011-08-20 04:43:34 +00:00
$this -> _createLinks ();
2008-09-22 16:32:41 +00:00
$this -> Behaviors -> init ( $this -> alias , $this -> actsAs );
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2011-12-26 17:36:48 +00:00
/**
* Returns a list of all events that will fire in the model during it ' s lifecycle .
2014-10-08 14:37:38 +00:00
* You can override this function to add your own listener callbacks
2011-12-26 17:36:48 +00:00
*
* @ return array
*/
public function implementedEvents () {
return array (
'Model.beforeFind' => array ( 'callable' => 'beforeFind' , 'passParams' => true ),
'Model.afterFind' => array ( 'callable' => 'afterFind' , 'passParams' => true ),
'Model.beforeValidate' => array ( 'callable' => 'beforeValidate' , 'passParams' => true ),
2012-05-07 04:08:29 +00:00
'Model.afterValidate' => array ( 'callable' => 'afterValidate' ),
2011-12-26 17:36:48 +00:00
'Model.beforeSave' => array ( 'callable' => 'beforeSave' , 'passParams' => true ),
'Model.afterSave' => array ( 'callable' => 'afterSave' , 'passParams' => true ),
2011-12-28 03:19:50 +00:00
'Model.beforeDelete' => array ( 'callable' => 'beforeDelete' , 'passParams' => true ),
2011-12-26 17:36:48 +00:00
'Model.afterDelete' => array ( 'callable' => 'afterDelete' ),
);
}
/**
* Returns the CakeEventManager manager instance that is handling any callbacks .
* You can use this instance to register any new listeners or callbacks to the
2012-02-17 12:51:20 +00:00
* model events , or create your own events and trigger them at will .
2011-12-26 17:36:48 +00:00
*
* @ return CakeEventManager
*/
public function getEventManager () {
if ( empty ( $this -> _eventManager )) {
$this -> _eventManager = new CakeEventManager ();
$this -> _eventManager -> attach ( $this -> Behaviors );
$this -> _eventManager -> attach ( $this );
}
2013-09-01 19:09:14 +00:00
2011-12-26 17:36:48 +00:00
return $this -> _eventManager ;
}
2008-05-30 11:40:08 +00:00
/**
* Handles custom method calls , like findBy < field > for DB models ,
* and custom RPC calls for remote data sources .
*
* @ param string $method Name of method to call .
* @ param array $params Parameters for the method .
* @ return mixed Whatever is returned by called method
*/
2010-04-05 06:43:20 +00:00
public function __call ( $method , $params ) {
2008-05-30 11:40:08 +00:00
$result = $this -> Behaviors -> dispatchMethod ( $this , $method , $params );
if ( $result !== array ( 'unhandled' )) {
return $result ;
}
2013-09-01 19:08:48 +00:00
return $this -> getDataSource () -> query ( $method , $params , $this );
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2010-07-14 21:28:12 +00:00
/**
2011-10-18 17:06:29 +00:00
* Handles the lazy loading of model associations by looking in the association arrays for the requested variable
2010-07-14 21:28:12 +00:00
*
2011-12-02 05:58:09 +00:00
* @ param string $name variable tested for existence in class
2014-07-03 13:36:42 +00:00
* @ return bool true if the variable exists ( if is a not loaded model association it will be created ), false otherwise
2010-07-14 21:28:12 +00:00
*/
public function __isset ( $name ) {
$className = false ;
2011-08-20 04:43:34 +00:00
foreach ( $this -> _associations as $type ) {
2010-07-14 21:28:12 +00:00
if ( isset ( $name , $this -> { $type }[ $name ])) {
$className = empty ( $this -> { $type }[ $name ][ 'className' ]) ? $name : $this -> { $type }[ $name ][ 'className' ];
break ;
2012-03-04 19:18:04 +00:00
} elseif ( isset ( $name , $this -> __backAssociation [ $type ][ $name ])) {
2011-09-29 14:44:05 +00:00
$className = empty ( $this -> __backAssociation [ $type ][ $name ][ 'className' ]) ?
$name : $this -> __backAssociation [ $type ][ $name ][ 'className' ];
break ;
2013-02-12 02:38:08 +00:00
} elseif ( $type === 'hasAndBelongsToMany' ) {
2010-07-14 21:28:12 +00:00
foreach ( $this -> { $type } as $k => $relation ) {
2010-07-14 22:24:19 +00:00
if ( empty ( $relation [ 'with' ])) {
continue ;
}
2013-09-01 19:09:14 +00:00
2010-07-15 03:49:38 +00:00
if ( is_array ( $relation [ 'with' ])) {
if ( key ( $relation [ 'with' ]) === $name ) {
$className = $name ;
}
2010-07-14 22:24:19 +00:00
} else {
list ( $plugin , $class ) = pluginSplit ( $relation [ 'with' ]);
if ( $class === $name ) {
$className = $relation [ 'with' ];
}
}
2013-09-01 19:09:14 +00:00
2010-07-14 22:24:19 +00:00
if ( $className ) {
$assocKey = $k ;
2010-07-15 03:49:38 +00:00
$dynamic = ! empty ( $relation [ 'dynamicWith' ]);
2010-07-14 21:28:12 +00:00
break ( 2 );
}
}
}
2011-12-19 13:18:28 +00:00
}
2010-07-14 21:28:12 +00:00
if ( ! $className ) {
return false ;
}
list ( $plugin , $className ) = pluginSplit ( $className );
2010-07-15 03:49:38 +00:00
if ( ! ClassRegistry :: isKeySet ( $className ) && ! empty ( $dynamic )) {
$this -> { $className } = new AppModel ( array (
'name' => $className ,
'table' => $this -> hasAndBelongsToMany [ $assocKey ][ 'joinTable' ],
'ds' => $this -> useDbConfig
));
} else {
2011-08-20 04:43:34 +00:00
$this -> _constructLinkedModel ( $name , $className , $plugin );
2010-07-15 03:49:38 +00:00
}
2010-07-14 22:24:19 +00:00
if ( ! empty ( $assocKey )) {
$this -> hasAndBelongsToMany [ $assocKey ][ 'joinTable' ] = $this -> { $name } -> table ;
if ( count ( $this -> { $name } -> schema ()) <= 2 && $this -> { $name } -> primaryKey !== false ) {
$this -> { $name } -> primaryKey = $this -> hasAndBelongsToMany [ $assocKey ][ 'foreignKey' ];
}
}
2010-07-16 03:47:13 +00:00
return true ;
2010-07-14 21:28:12 +00:00
}
/**
* Returns the value of the requested variable if it can be set by __isset ()
*
* @ param string $name variable requested for it ' s value or reference
* @ return mixed value of requested variable if it is set
*/
2011-05-28 20:38:46 +00:00
public function __get ( $name ) {
2010-07-16 01:48:16 +00:00
if ( $name === 'displayField' ) {
return $this -> displayField = $this -> hasField ( array ( 'title' , 'name' , $this -> primaryKey ));
}
2013-09-01 19:09:14 +00:00
2011-12-08 04:40:22 +00:00
if ( $name === 'tablePrefix' ) {
$this -> setDataSource ();
2012-01-11 02:01:03 +00:00
if ( property_exists ( $this , 'tablePrefix' ) && ! empty ( $this -> tablePrefix )) {
2011-12-08 04:40:22 +00:00
return $this -> tablePrefix ;
}
2013-09-01 19:09:14 +00:00
2011-12-08 04:40:22 +00:00
return $this -> tablePrefix = null ;
}
2013-09-01 19:09:14 +00:00
2010-07-14 21:28:12 +00:00
if ( isset ( $this -> { $name })) {
return $this -> { $name };
}
}
2008-05-30 11:40:08 +00:00
/**
* Bind model associations on the fly .
*
2010-05-01 21:37:23 +00:00
* If `$reset` is false , association will not be reset
2008-05-30 11:40:08 +00:00
* to the originals defined in the model
*
* Example : Add a new hasOne binding to the Profile model not
* defined in the model source code :
2010-05-01 21:37:23 +00:00
*
2013-10-24 11:05:32 +00:00
* `$this->User->bindModel(array('hasOne' => array('Profile')));`
2010-05-01 21:37:23 +00:00
*
* Bindings that are not made permanent will be reset by the next Model :: find () call on this
* model .
2008-05-30 11:40:08 +00:00
*
* @ param array $params Set of bindings ( indexed by binding type )
2014-07-03 13:36:42 +00:00
* @ param bool $reset Set to false to make the binding permanent
* @ return bool Success
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / associations - linking - models - together . html #creating-and-destroying-associations-on-the-fly
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function bindModel ( $params , $reset = true ) {
2008-05-30 11:40:08 +00:00
foreach ( $params as $assoc => $model ) {
2010-07-03 22:05:14 +00:00
if ( $reset === true && ! isset ( $this -> __backAssociation [ $assoc ])) {
2008-05-30 11:40:08 +00:00
$this -> __backAssociation [ $assoc ] = $this -> { $assoc };
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
foreach ( $model as $key => $value ) {
$assocName = $key ;
if ( is_numeric ( $key )) {
$assocName = $value ;
$value = array ();
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
$this -> { $assoc }[ $assocName ] = $value ;
2013-09-01 19:09:14 +00:00
2010-07-14 21:28:12 +00:00
if ( property_exists ( $this , $assocName )) {
unset ( $this -> { $assocName });
}
2013-09-01 19:09:14 +00:00
2010-07-01 16:39:50 +00:00
if ( $reset === false && isset ( $this -> __backAssociation [ $assoc ])) {
$this -> __backAssociation [ $assoc ][ $assocName ] = $value ;
}
2008-05-30 11:40:08 +00:00
}
}
2013-09-01 19:09:14 +00:00
2011-08-20 04:43:34 +00:00
$this -> _createLinks ();
2008-05-30 11:40:08 +00:00
return true ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* 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 :
2010-11-03 13:25:42 +00:00
*
2013-10-24 13:13:22 +00:00
* `$this->User->unbindModel(array('hasMany' => array('SupportRequest')));`
* Or alternatively :
* `$this->User->unbindModel(array('hasMany' => 'SupportRequest'));`
2010-11-03 13:25:42 +00:00
*
2013-10-24 13:13:22 +00:00
* Unbound models that are not made permanent will reset with the next call to Model :: find ()
2008-05-30 11:40:08 +00:00
*
* @ param array $params Set of bindings to unbind ( indexed by binding type )
2014-07-03 13:36:42 +00:00
* @ param bool $reset Set to false to make the unbinding permanent
* @ return bool Success
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / associations - linking - models - together . html #creating-and-destroying-associations-on-the-fly
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function unbindModel ( $params , $reset = true ) {
2008-05-30 11:40:08 +00:00
foreach ( $params as $assoc => $models ) {
2010-07-03 22:05:14 +00:00
if ( $reset === true && ! isset ( $this -> __backAssociation [ $assoc ])) {
2008-05-30 11:40:08 +00:00
$this -> __backAssociation [ $assoc ] = $this -> { $assoc };
}
2013-10-24 13:13:22 +00:00
$models = Hash :: normalize (( array ) $models , false );
2008-05-30 11:40:08 +00:00
foreach ( $models as $model ) {
2010-07-03 22:05:14 +00:00
if ( $reset === false && isset ( $this -> __backAssociation [ $assoc ][ $model ])) {
unset ( $this -> __backAssociation [ $assoc ][ $model ]);
}
2013-09-01 19:09:14 +00:00
2010-07-01 16:39:50 +00:00
unset ( $this -> { $assoc }[ $model ]);
2008-05-30 11:40:08 +00:00
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return true ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Create a set of associations .
2008-05-30 11:40:08 +00:00
*
2008-09-25 16:49:56 +00:00
* @ return void
2008-05-30 11:40:08 +00:00
*/
2011-08-20 04:43:34 +00:00
protected function _createLinks () {
foreach ( $this -> _associations as $type ) {
2013-10-24 01:38:03 +00:00
$association =& $this -> { $type };
2008-05-30 11:40:08 +00:00
2013-10-24 01:38:03 +00:00
if ( ! is_array ( $association )) {
$association = explode ( ',' , $association );
foreach ( $association as $i => $className ) {
2008-05-30 11:40:08 +00:00
$className = trim ( $className );
2013-10-24 01:38:03 +00:00
unset ( $association [ $i ]);
$association [ $className ] = array ();
2008-05-30 11:40:08 +00:00
}
}
2013-10-24 01:38:03 +00:00
if ( ! empty ( $association )) {
foreach ( $association as $assoc => $value ) {
2008-06-11 08:54:27 +00:00
$plugin = null ;
2008-05-30 11:40:08 +00:00
2008-06-11 08:54:27 +00:00
if ( is_numeric ( $assoc )) {
2013-10-24 01:38:03 +00:00
unset ( $association [ $assoc ]);
2008-06-11 08:54:27 +00:00
$assoc = $value ;
$value = array ();
if ( strpos ( $assoc , '.' ) !== false ) {
2012-03-22 11:18:57 +00:00
list ( $plugin , $assoc ) = pluginSplit ( $assoc , true );
2013-10-24 01:38:03 +00:00
$association [ $assoc ] = array ( 'className' => $plugin . $assoc );
2011-09-18 16:26:59 +00:00
} else {
2013-10-24 01:38:03 +00:00
$association [ $assoc ] = $value ;
2008-06-11 08:54:27 +00:00
}
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2011-08-20 04:43:34 +00:00
$this -> _generateAssociation ( $type , $assoc );
2008-05-30 11:40:08 +00:00
}
}
}
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2011-08-20 04:43:34 +00:00
* Protected helper method to create associated models of a given class .
2008-05-30 11:40:08 +00:00
*
* @ param string $assoc Association name
* @ param string $className Class name
2010-07-14 03:58:48 +00:00
* @ param string $plugin name of the plugin where $className is located
2010-04-04 07:14:00 +00:00
* examples : public $hasMany = array ( 'Assoc' => array ( 'className' => 'ModelName' ));
2008-05-30 11:40:08 +00:00
* usage : $this -> Assoc -> modelMethods ();
*
2010-04-04 07:14:00 +00:00
* public $hasMany = array ( 'ModelName' );
2008-05-30 11:40:08 +00:00
* usage : $this -> ModelName -> modelMethods ();
2008-09-25 16:49:56 +00:00
* @ return void
2008-05-30 11:40:08 +00:00
*/
2011-08-20 04:43:34 +00:00
protected function _constructLinkedModel ( $assoc , $className = null , $plugin = null ) {
2008-10-23 00:10:44 +00:00
if ( empty ( $className )) {
2008-05-30 11:40:08 +00:00
$className = $assoc ;
}
2008-09-19 15:27:43 +00:00
if ( ! isset ( $this -> { $assoc }) || $this -> { $assoc } -> name !== $className ) {
2011-07-14 06:00:52 +00:00
if ( $plugin ) {
$plugin .= '.' ;
}
2013-09-01 19:09:14 +00:00
2011-07-14 06:00:52 +00:00
$model = array ( 'class' => $plugin . $className , 'alias' => $assoc );
2010-07-06 02:19:22 +00:00
$this -> { $assoc } = ClassRegistry :: init ( $model );
2013-09-01 19:09:14 +00:00
2010-07-14 23:53:41 +00:00
if ( $plugin ) {
2011-07-14 06:00:52 +00:00
ClassRegistry :: addObject ( $plugin . $className , $this -> { $assoc });
2010-01-18 17:35:30 +00:00
}
2013-09-01 19:09:14 +00:00
2008-06-11 08:54:27 +00:00
if ( $assoc ) {
$this -> tableToModel [ $this -> { $assoc } -> table ] = $assoc ;
}
2008-05-30 11:40:08 +00:00
}
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Build an array - based association from string .
2008-05-30 11:40:08 +00:00
*
* @ param string $type 'belongsTo' , 'hasOne' , 'hasMany' , 'hasAndBelongsToMany'
2014-06-04 18:58:55 +00:00
* @ param string $assocKey Association key .
2008-09-25 16:49:56 +00:00
* @ return void
2008-05-30 11:40:08 +00:00
*/
2011-08-20 04:43:34 +00:00
protected function _generateAssociation ( $type , $assocKey ) {
2010-07-14 21:28:12 +00:00
$class = $assocKey ;
$dynamicWith = false ;
2013-10-24 01:38:03 +00:00
$assoc =& $this -> { $type }[ $assocKey ];
2008-05-30 11:40:08 +00:00
2011-08-20 04:43:34 +00:00
foreach ( $this -> _associationKeys [ $type ] as $key ) {
2013-10-24 01:38:03 +00:00
if ( ! isset ( $assoc [ $key ]) || $assoc [ $key ] === null ) {
2010-07-14 21:28:12 +00:00
$data = '' ;
2008-05-30 11:40:08 +00:00
2010-07-14 21:28:12 +00:00
switch ( $key ) {
case 'fields' :
$data = '' ;
2013-07-02 22:52:48 +00:00
break ;
2008-05-30 11:40:08 +00:00
2010-07-14 21:28:12 +00:00
case 'foreignKey' :
2013-02-12 02:38:08 +00:00
$data = (( $type === 'belongsTo' ) ? Inflector :: underscore ( $assocKey ) : Inflector :: singularize ( $this -> table )) . '_id' ;
2013-07-02 22:52:48 +00:00
break ;
2008-05-30 11:40:08 +00:00
2010-07-14 21:28:12 +00:00
case 'associationForeignKey' :
$data = Inflector :: singularize ( $this -> { $class } -> table ) . '_id' ;
2013-07-02 22:52:48 +00:00
break ;
2008-05-30 11:40:08 +00:00
2010-07-14 21:28:12 +00:00
case 'with' :
2013-10-24 01:38:03 +00:00
$data = Inflector :: camelize ( Inflector :: singularize ( $assoc [ 'joinTable' ]));
2010-07-14 21:28:12 +00:00
$dynamicWith = true ;
2013-07-02 22:52:48 +00:00
break ;
2008-05-30 11:40:08 +00:00
2010-07-14 21:28:12 +00:00
case 'joinTable' :
$tables = array ( $this -> table , $this -> { $class } -> table );
2013-05-13 18:21:32 +00:00
sort ( $tables );
2010-07-14 21:28:12 +00:00
$data = $tables [ 0 ] . '_' . $tables [ 1 ];
2013-07-02 22:52:48 +00:00
break ;
2008-05-30 11:40:08 +00:00
2010-07-14 21:28:12 +00:00
case 'className' :
$data = $class ;
2013-07-02 22:52:48 +00:00
break ;
2008-05-30 11:40:08 +00:00
2010-07-14 21:28:12 +00:00
case 'unique' :
$data = true ;
2013-07-02 22:52:48 +00:00
break ;
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
$assoc [ $key ] = $data ;
2008-05-30 11:40:08 +00:00
}
2010-07-15 03:49:38 +00:00
if ( $dynamicWith ) {
2013-10-24 01:38:03 +00:00
$assoc [ 'dynamicWith' ] = true ;
2010-07-14 21:28:12 +00:00
}
2008-05-30 11:40:08 +00:00
}
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2012-10-11 07:03:46 +00:00
* Sets a custom table for your model class . Used by your controller to select a database table .
2008-05-30 11:40:08 +00:00
*
* @ param string $tableName Name of the custom table
2010-07-16 03:41:30 +00:00
* @ throws MissingTableException when database table $tableName is not found on data source
2008-09-25 16:49:56 +00:00
* @ return void
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function setSource ( $tableName ) {
2008-05-30 11:40:08 +00:00
$this -> setDataSource ( $this -> useDbConfig );
2010-07-16 01:46:52 +00:00
$db = ConnectionManager :: getDataSource ( $this -> useDbConfig );
2008-05-30 11:40:08 +00:00
2011-02-25 01:51:43 +00:00
if ( method_exists ( $db , 'listSources' )) {
2013-11-19 20:06:55 +00:00
$restore = $db -> cacheSources ;
2013-11-19 22:32:31 +00:00
$db -> cacheSources = ( $restore && $this -> cacheSources );
2008-05-30 11:40:08 +00:00
$sources = $db -> listSources ();
2013-11-19 20:06:55 +00:00
$db -> cacheSources = $restore ;
2008-05-30 11:40:08 +00:00
if ( is_array ( $sources ) && ! in_array ( strtolower ( $this -> tablePrefix . $tableName ), array_map ( 'strtolower' , $sources ))) {
2010-08-30 01:37:25 +00:00
throw new MissingTableException ( array (
'table' => $this -> tablePrefix . $tableName ,
2011-11-05 06:50:11 +00:00
'class' => $this -> alias ,
'ds' => $this -> useDbConfig ,
2010-08-30 01:37:25 +00:00
));
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2013-12-16 19:42:21 +00:00
if ( $sources ) {
$this -> _schema = null ;
}
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
$this -> table = $this -> useTable = $tableName ;
$this -> tableToModel [ $this -> table ] = $this -> alias ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2009-11-12 04:17:23 +00:00
* This function does two things :
2009-10-06 01:27:34 +00:00
*
* 1. it scans the array $one for the primary key ,
2008-05-30 11:40:08 +00:00
* 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 .
2009-10-06 01:27:34 +00:00
* 2. Returns an array with all of $one ' s keys and values .
2008-05-30 11:40:08 +00:00
* ( Alternative indata : two strings , which are mangled to
* a one - item , two - dimensional array using $one for a key and $two as its value . )
*
2012-05-13 00:43:31 +00:00
* @ param string | array | SimpleXmlElement | DomNode $one Array or string of data
2008-05-30 11:40:08 +00:00
* @ param string $two Value string for the alternative indata method
* @ return array Data with all of $one ' s keys and values
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / saving - your - data . html
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function set ( $one , $two = null ) {
2008-05-30 11:40:08 +00:00
if ( ! $one ) {
return ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( is_object ( $one )) {
2010-10-18 00:47:43 +00:00
if ( $one instanceof SimpleXMLElement || $one instanceof DOMNode ) {
$one = $this -> _normalizeXmlData ( Xml :: toArray ( $one ));
} else {
$one = Set :: reverse ( $one );
}
2008-05-30 11:40:08 +00:00
}
if ( is_array ( $one )) {
2008-06-14 20:39:27 +00:00
$data = $one ;
if ( empty ( $one [ $this -> alias ])) {
2012-05-15 14:57:42 +00:00
$data = $this -> _setAliasData ( $one );
2008-05-30 11:40:08 +00:00
}
} else {
$data = array ( $this -> alias => array ( $one => $two ));
}
2008-10-06 02:44:05 +00:00
foreach ( $data as $modelName => $fieldSet ) {
2013-10-24 01:38:03 +00:00
if ( ! is_array ( $fieldSet )) {
continue ;
}
2008-05-30 11:40:08 +00:00
2014-08-28 22:49:30 +00:00
if ( ! isset ( $this -> data [ $modelName ])) {
$this -> data [ $modelName ] = array ();
}
2013-10-24 01:38:03 +00:00
foreach ( $fieldSet as $fieldName => $fieldValue ) {
unset ( $this -> validationErrors [ $fieldName ]);
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
if ( $modelName === $this -> alias && $fieldName === $this -> primaryKey ) {
$this -> id = $fieldValue ;
}
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
if ( is_array ( $fieldValue ) || is_object ( $fieldValue )) {
$fieldValue = $this -> deconstruct ( $fieldName , $fieldValue );
2008-05-30 11:40:08 +00:00
}
2013-10-24 01:38:03 +00:00
$this -> data [ $modelName ][ $fieldName ] = $fieldValue ;
2008-05-30 11:40:08 +00:00
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return $data ;
}
2009-07-24 19:18:37 +00:00
2012-05-15 14:57:42 +00:00
/**
* Move values to alias
*
2014-06-04 18:58:55 +00:00
* @ param array $data Data .
2012-05-15 14:57:42 +00:00
* @ return array
*/
protected function _setAliasData ( $data ) {
$models = array_keys ( $this -> getAssociated ());
2012-06-01 23:39:53 +00:00
$schema = array_keys (( array ) $this -> schema ());
2013-09-01 19:09:14 +00:00
2012-05-15 14:57:42 +00:00
foreach ( $data as $field => $value ) {
if ( in_array ( $field , $schema ) || ! in_array ( $field , $models )) {
$data [ $this -> alias ][ $field ] = $value ;
unset ( $data [ $field ]);
}
}
2013-09-01 19:09:14 +00:00
2012-05-15 14:57:42 +00:00
return $data ;
}
2010-10-18 00:47:43 +00:00
/**
2013-04-07 18:56:59 +00:00
* Normalize `Xml::toArray()` to use in `Model::save()`
2010-10-18 00:47:43 +00:00
*
* @ param array $xml XML as array
* @ return array
*/
protected function _normalizeXmlData ( array $xml ) {
$return = array ();
foreach ( $xml as $key => $value ) {
if ( is_array ( $value )) {
$return [ Inflector :: camelize ( $key )] = $this -> _normalizeXmlData ( $value );
} elseif ( $key [ 0 ] === '@' ) {
$return [ substr ( $key , 1 )] = $value ;
} else {
$return [ $key ] = $value ;
}
}
2013-09-01 19:09:14 +00:00
2010-10-18 00:47:43 +00:00
return $return ;
}
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Deconstructs a complex data type ( array or object ) into a single field value .
2008-05-30 11:40:08 +00:00
*
* @ param string $field The name of the field to be deconstructed
2012-05-13 00:43:31 +00:00
* @ param array | object $data An array or object to be deconstructed into a field
2008-05-30 11:40:08 +00:00
* @ return mixed The resulting data that should be assigned to a field
*/
2010-04-05 03:19:38 +00:00
public function deconstruct ( $field , $data ) {
2009-06-02 03:23:15 +00:00
if ( ! is_array ( $data )) {
return $data ;
}
2008-05-30 11:40:08 +00:00
$type = $this -> getColumnType ( $field );
2012-12-03 15:30:03 +00:00
if ( ! in_array ( $type , array ( 'datetime' , 'timestamp' , 'date' , 'time' ))) {
return $data ;
}
2009-07-08 03:25:30 +00:00
2012-12-03 15:30:03 +00:00
$useNewDate = ( isset ( $data [ 'year' ]) || isset ( $data [ 'month' ]) ||
isset ( $data [ 'day' ]) || isset ( $data [ 'hour' ]) || isset ( $data [ 'minute' ]));
2008-05-30 11:40:08 +00:00
2012-12-03 15:30:03 +00:00
$dateFields = array ( 'Y' => 'year' , 'm' => 'month' , 'd' => 'day' , 'H' => 'hour' , 'i' => 'min' , 's' => 'sec' );
$timeFields = array ( 'H' => 'hour' , 'i' => 'min' , 's' => 'sec' );
$date = array ();
2011-12-26 15:03:14 +00:00
2012-12-03 15:30:03 +00:00
if ( isset ( $data [ 'meridian' ]) && empty ( $data [ 'meridian' ])) {
return null ;
}
2014-12-09 02:17:35 +00:00
if ( isset ( $data [ 'hour' ]) &&
2012-12-03 15:30:03 +00:00
isset ( $data [ 'meridian' ]) &&
! empty ( $data [ 'hour' ]) &&
$data [ 'hour' ] != 12 &&
2013-07-03 17:27:17 +00:00
$data [ 'meridian' ] === 'pm'
2012-12-03 15:30:03 +00:00
) {
$data [ 'hour' ] = $data [ 'hour' ] + 12 ;
}
2013-09-01 19:09:14 +00:00
2013-07-03 17:27:17 +00:00
if ( isset ( $data [ 'hour' ]) && isset ( $data [ 'meridian' ]) && $data [ 'hour' ] == 12 && $data [ 'meridian' ] === 'am' ) {
2012-12-03 15:30:03 +00:00
$data [ 'hour' ] = '00' ;
}
2013-09-01 19:09:14 +00:00
2013-02-12 02:38:08 +00:00
if ( $type === 'time' ) {
2012-12-03 15:30:03 +00:00
foreach ( $timeFields as $key => $val ) {
if ( ! isset ( $data [ $val ]) || $data [ $val ] === '0' || $data [ $val ] === '00' ) {
$data [ $val ] = '00' ;
} elseif ( $data [ $val ] !== '' ) {
$data [ $val ] = sprintf ( '%02d' , $data [ $val ]);
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( ! empty ( $data [ $val ])) {
$date [ $key ] = $data [ $val ];
} else {
return null ;
}
2008-05-30 11:40:08 +00:00
}
2012-12-03 15:30:03 +00:00
}
2013-02-12 02:38:08 +00:00
if ( $type === 'datetime' || $type === 'timestamp' || $type === 'date' ) {
2012-12-03 15:30:03 +00:00
foreach ( $dateFields as $key => $val ) {
2013-02-12 02:38:08 +00:00
if ( $val === 'hour' || $val === 'min' || $val === 'sec' ) {
2009-07-08 03:25:30 +00:00
if ( ! isset ( $data [ $val ]) || $data [ $val ] === '0' || $data [ $val ] === '00' ) {
2008-05-30 11:40:08 +00:00
$data [ $val ] = '00' ;
2009-07-08 03:25:30 +00:00
} else {
2012-12-03 15:30:03 +00:00
$data [ $val ] = sprintf ( '%02d' , $data [ $val ]);
2009-07-08 03:25:30 +00:00
}
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( ! isset ( $data [ $val ]) || isset ( $data [ $val ]) && ( empty ( $data [ $val ]) || $data [ $val ][ 0 ] === '-' )) {
return null ;
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( isset ( $data [ $val ]) && ! empty ( $data [ $val ])) {
$date [ $key ] = $data [ $val ];
2008-05-30 11:40:08 +00:00
}
}
2012-12-03 15:30:03 +00:00
}
2010-11-27 04:43:04 +00:00
2012-12-03 15:30:03 +00:00
if ( $useNewDate && ! empty ( $date )) {
$format = $this -> getDataSource () -> columns [ $type ][ 'format' ];
foreach ( array ( 'm' , 'd' , 'H' , 'i' , 's' ) as $index ) {
if ( isset ( $date [ $index ])) {
$date [ $index ] = sprintf ( '%02d' , $date [ $index ]);
2011-12-03 19:38:55 +00:00
}
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
return str_replace ( array_keys ( $date ), array_values ( $date ), $format );
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return $data ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* Returns an array of table metadata ( column names and types ) from the database .
* $field => keys ( type , null , default , key , length , extra )
*
2014-07-03 13:36:42 +00:00
* @ param bool | string $field Set to true to reload schema , or a string to return a specific field
2014-11-05 12:03:27 +00:00
* @ return array | null Array of table metadata
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function schema ( $field = false ) {
2012-01-21 18:33:11 +00:00
if ( $this -> useTable !== false && ( ! is_array ( $this -> _schema ) || $field === true )) {
2010-07-15 03:49:38 +00:00
$db = $this -> getDataSource ();
2008-08-27 04:55:15 +00:00
$db -> cacheSources = ( $this -> cacheSources && $db -> cacheSources );
2012-12-20 02:18:34 +00:00
if ( method_exists ( $db , 'describe' )) {
2011-07-11 19:07:44 +00:00
$this -> _schema = $db -> describe ( $this );
2008-05-30 11:40:08 +00:00
}
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( ! is_string ( $field )) {
return $this -> _schema ;
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( isset ( $this -> _schema [ $field ])) {
return $this -> _schema [ $field ];
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
return null ;
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* Returns an associative array of field names and column types .
*
* @ return array Field types indexed by field name
*/
2010-04-05 03:19:38 +00:00
public function getColumnTypes () {
2008-05-30 11:40:08 +00:00
$columns = $this -> schema ();
if ( empty ( $columns )) {
2011-03-20 15:35:43 +00:00
trigger_error ( __d ( 'cake_dev' , '(Model::getColumnTypes) Unable to build model field data. If you are using a model without a database table, try implementing schema()' ), E_USER_WARNING );
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
$cols = array ();
foreach ( $columns as $field => $values ) {
$cols [ $field ] = $values [ 'type' ];
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return $cols ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns the column type of a column in the model .
2008-05-30 11:40:08 +00:00
*
* @ param string $column The name of the model column
* @ return string Column type
*/
2010-04-05 03:19:38 +00:00
public function getColumnType ( $column ) {
2008-05-30 11:40:08 +00:00
$cols = $this -> schema ();
2015-01-21 22:04:29 +00:00
if ( isset ( $cols [ $column ]) && isset ( $cols [ $column ][ 'type' ])) {
return $cols [ $column ][ 'type' ];
}
$db = $this -> getDataSource ();
2008-05-30 11:40:08 +00:00
$model = null ;
2012-04-11 17:08:45 +00:00
$startQuote = isset ( $db -> startQuote ) ? $db -> startQuote : null ;
$endQuote = isset ( $db -> endQuote ) ? $db -> endQuote : null ;
$column = str_replace ( array ( $startQuote , $endQuote ), '' , $column );
2008-11-10 19:53:04 +00:00
2008-05-30 11:40:08 +00:00
if ( strpos ( $column , '.' )) {
list ( $model , $column ) = explode ( '.' , $column );
}
2013-09-01 19:09:14 +00:00
2014-03-10 17:16:32 +00:00
if ( isset ( $model ) && $model != $this -> alias && isset ( $this -> { $model })) {
2008-05-30 11:40:08 +00:00
return $this -> { $model } -> getColumnType ( $column );
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( isset ( $cols [ $column ]) && isset ( $cols [ $column ][ 'type' ])) {
return $cols [ $column ][ 'type' ];
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return null ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns true if the supplied field exists in the model ' s database table .
2008-05-30 11:40:08 +00:00
*
2012-05-13 00:43:31 +00:00
* @ param string | array $name Name of field to look for , or an array of names
2014-07-03 13:36:42 +00:00
* @ param bool $checkVirtual checks if the field is declared as virtual
2008-05-30 11:40:08 +00:00
* @ return 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 .
*/
2010-04-05 03:19:38 +00:00
public function hasField ( $name , $checkVirtual = false ) {
2008-05-30 11:40:08 +00:00
if ( is_array ( $name )) {
foreach ( $name as $n ) {
2009-12-17 05:15:42 +00:00
if ( $this -> hasField ( $n , $checkVirtual )) {
2008-05-30 11:40:08 +00:00
return $n ;
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return false ;
}
2012-12-03 15:30:03 +00:00
if ( $checkVirtual && ! empty ( $this -> virtualFields ) && $this -> isVirtualField ( $name )) {
return true ;
2009-11-12 05:09:11 +00:00
}
2008-05-30 11:40:08 +00:00
if ( empty ( $this -> _schema )) {
$this -> schema ();
}
2012-09-21 22:30:43 +00:00
if ( $this -> _schema ) {
2008-05-30 11:40:08 +00:00
return isset ( $this -> _schema [ $name ]);
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return false ;
}
2009-07-24 19:18:37 +00:00
2010-12-26 22:35:22 +00:00
/**
2012-12-22 22:48:15 +00:00
* Check that a method is callable on a model . This will check both the model ' s own methods , its
2010-12-26 22:35:22 +00:00
* inherited methods and methods that could be callable through behaviors .
*
* @ param string $method The method to be called .
2014-07-03 13:36:42 +00:00
* @ return bool True on method being callable .
2010-12-26 22:35:22 +00:00
*/
public function hasMethod ( $method ) {
if ( method_exists ( $this , $method )) {
return true ;
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
return $this -> Behaviors -> hasMethod ( $method );
2010-12-26 22:35:22 +00:00
}
2009-12-07 02:46:00 +00:00
/**
* Returns true if the supplied field is a model Virtual Field
*
2011-07-30 22:38:57 +00:00
* @ param string $field Name of field to look for
2014-07-03 13:36:42 +00:00
* @ return bool indicating whether the field exists as a model virtual field .
2009-12-07 02:46:00 +00:00
*/
2010-04-05 03:19:38 +00:00
public function isVirtualField ( $field ) {
2010-01-19 14:22:13 +00:00
if ( empty ( $this -> virtualFields ) || ! is_string ( $field )) {
return false ;
}
2013-09-01 19:09:14 +00:00
2010-01-19 14:22:13 +00:00
if ( isset ( $this -> virtualFields [ $field ])) {
return true ;
}
2013-09-01 19:09:14 +00:00
2010-01-19 14:22:13 +00:00
if ( strpos ( $field , '.' ) !== false ) {
list ( $model , $field ) = explode ( '.' , $field );
2014-04-29 12:19:33 +00:00
if ( $model === $this -> alias && isset ( $this -> virtualFields [ $field ])) {
2010-01-19 14:22:13 +00:00
return true ;
}
}
2013-09-01 19:09:14 +00:00
2010-01-19 14:22:13 +00:00
return false ;
2009-12-07 02:46:00 +00:00
}
/**
2010-01-14 17:57:43 +00:00
* Returns the expression for a model virtual field
2009-12-07 02:46:00 +00:00
*
2011-07-30 22:38:57 +00:00
* @ param string $field Name of field to look for
2009-12-07 02:46:00 +00:00
* @ return mixed If $field is string expression bound to virtual field $field
2009-12-20 21:26:12 +00:00
* If $field is null , returns an array of all model virtual fields
* or false if none $field exist .
2009-12-07 02:46:00 +00:00
*/
2010-04-05 03:19:38 +00:00
public function getVirtualField ( $field = null ) {
2012-09-14 17:26:30 +00:00
if ( ! $field ) {
2009-12-07 02:46:00 +00:00
return empty ( $this -> virtualFields ) ? false : $this -> virtualFields ;
}
2013-09-01 19:09:14 +00:00
2009-12-07 02:46:00 +00:00
if ( $this -> isVirtualField ( $field )) {
2010-01-19 14:22:13 +00:00
if ( strpos ( $field , '.' ) !== false ) {
2012-12-03 15:30:03 +00:00
list (, $field ) = pluginSplit ( $field );
2010-01-19 14:22:13 +00:00
}
2013-09-01 19:09:14 +00:00
2009-12-07 02:46:00 +00:00
return $this -> virtualFields [ $field ];
}
2013-09-01 19:09:14 +00:00
2009-12-07 02:46:00 +00:00
return false ;
}
2008-05-30 11:40:08 +00:00
/**
* Initializes the model for writing a new record , loading the default values
2009-11-12 04:17:23 +00:00
* for those fields that are not defined in $data , and clearing previous validation errors .
2009-10-13 03:38:55 +00:00
* Especially helpful for saving data in loops .
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ param bool | array $data Optional data array to assign to the model after it is created . If null or false ,
2009-10-13 03:38:55 +00:00
* schema data defaults are not merged .
2014-07-03 13:36:42 +00:00
* @ param bool $filterKey If true , overwrites any primary key input with an empty value
2008-05-30 11:40:08 +00:00
* @ return array The current Model :: data ; after merging $data and / or defaults from database
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / saving - your - data . html #model-create-array-data-array
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function create ( $data = array (), $filterKey = false ) {
2008-05-30 11:40:08 +00:00
$defaults = array ();
$this -> id = false ;
$this -> data = array ();
$this -> validationErrors = array ();
if ( $data !== null && $data !== false ) {
2012-12-20 02:18:34 +00:00
$schema = ( array ) $this -> schema ();
foreach ( $schema as $field => $properties ) {
2011-01-21 18:31:33 +00:00
if ( $this -> primaryKey !== $field && isset ( $properties [ 'default' ]) && $properties [ 'default' ] !== '' ) {
2008-05-30 11:40:08 +00:00
$defaults [ $field ] = $properties [ 'default' ];
}
}
2013-09-01 19:09:14 +00:00
2011-01-21 18:31:33 +00:00
$this -> set ( $defaults );
2008-05-30 11:40:08 +00:00
$this -> set ( $data );
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( $filterKey ) {
$this -> set ( $this -> primaryKey , false );
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return $this -> data ;
}
2013-06-08 11:53:35 +00:00
2013-06-04 21:59:54 +00:00
/**
2013-06-08 11:53:35 +00:00
* This function is a convenient wrapper class to create ( false ) and , as the name suggests , clears the id , data , and validation errors .
*
2014-07-03 13:36:42 +00:00
* @ return bool Always true upon success
2013-06-08 11:53:35 +00:00
* @ see Model :: create ()
*/
2013-06-04 21:59:54 +00:00
public function clear () {
$this -> create ( false );
return true ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* Returns a list of fields from the database , and sets the current model
* data ( Model :: $data ) with the record found .
*
2012-05-13 00:43:31 +00:00
* @ param string | array $fields String of single field name , or an array of field names .
2014-07-03 13:36:42 +00:00
* @ param int | string $id The ID of the record to read
2008-05-30 11:40:08 +00:00
* @ return array Array of database fields , or false if not found
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / retrieving - your - data . html #model-read
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function read ( $fields = null , $id = null ) {
2008-05-30 11:40:08 +00:00
$this -> validationErrors = array ();
2012-09-21 22:30:43 +00:00
if ( $id ) {
2008-05-30 11:40:08 +00:00
$this -> id = $id ;
}
$id = $this -> id ;
if ( is_array ( $this -> id )) {
$id = $this -> id [ 0 ];
}
if ( $id !== null && $id !== false ) {
2009-05-04 22:57:10 +00:00
$this -> data = $this -> find ( 'first' , array (
'conditions' => array ( $this -> alias . '.' . $this -> primaryKey => $id ),
'fields' => $fields
));
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return $this -> data ;
}
2013-09-01 19:09:14 +00:00
2012-09-21 22:30:43 +00:00
return false ;
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns the contents of a single field given the supplied conditions , in the
* supplied order .
2008-05-30 11:40:08 +00:00
*
* @ param string $name Name of field to get
* @ param array $conditions SQL conditions ( defaults to NULL )
* @ param string $order SQL ORDER BY fragment
* @ return string field contents , or false if not found
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / retrieving - your - data . html #model-field
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function field ( $name , $conditions = null , $order = null ) {
2008-05-30 11:40:08 +00:00
if ( $conditions === null && $this -> id !== false ) {
$conditions = array ( $this -> alias . '.' . $this -> primaryKey => $this -> id );
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
$recursive = $this -> recursive ;
2008-05-30 11:40:08 +00:00
if ( $this -> recursive >= 1 ) {
$recursive = - 1 ;
}
2013-09-01 19:09:14 +00:00
2009-11-12 04:13:37 +00:00
$fields = $name ;
2012-12-03 15:30:03 +00:00
$data = $this -> find ( 'first' , compact ( 'conditions' , 'fields' , 'order' , 'recursive' ));
if ( ! $data ) {
return false ;
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( strpos ( $name , '.' ) === false ) {
if ( isset ( $data [ $this -> alias ][ $name ])) {
return $data [ $this -> alias ][ $name ];
2008-05-30 11:40:08 +00:00
}
} else {
2012-12-03 15:30:03 +00:00
$name = explode ( '.' , $name );
if ( isset ( $data [ $name [ 0 ]][ $name [ 1 ]])) {
return $data [ $name [ 0 ]][ $name [ 1 ]];
}
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( isset ( $data [ 0 ]) && count ( $data [ 0 ]) > 0 ) {
return array_shift ( $data [ 0 ]);
2008-05-30 11:40:08 +00:00
}
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Saves the value of a single field to the database , based on the current
* model ID .
2008-05-30 11:40:08 +00:00
*
* @ param string $name Name of the table field
* @ param mixed $value Value of the field
2014-07-03 13:36:42 +00:00
* @ param bool | array $validate Either a boolean , or an array .
2012-12-10 19:14:42 +00:00
* If a boolean , indicates whether or not to validate before saving .
2013-01-29 03:40:42 +00:00
* If an array , allows control of 'validate' , 'callbacks' and 'counterCache' options .
* See Model :: save () for details of each options .
2014-11-06 01:37:43 +00:00
* @ return bool | array See Model :: save () False on failure or an array of model data on success .
2008-05-30 11:40:08 +00:00
* @ see Model :: save ()
2012-01-25 09:12:59 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / saving - your - data . html #model-savefield-string-fieldname-string-fieldvalue-validate-false
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function saveField ( $name , $value , $validate = false ) {
2008-05-30 11:40:08 +00:00
$id = $this -> id ;
$this -> create ( false );
2008-06-20 20:17:23 +00:00
2012-12-03 15:30:03 +00:00
$options = array ( 'validate' => $validate , 'fieldList' => array ( $name ));
2008-06-20 20:17:23 +00:00
if ( is_array ( $validate )) {
2014-04-07 23:25:14 +00:00
$options = $validate + array ( 'validate' => false , 'fieldList' => array ( $name ));
2008-06-20 20:17:23 +00:00
}
2013-09-01 19:09:14 +00:00
2008-07-05 11:02:09 +00:00
return $this -> save ( array ( $this -> alias => array ( $this -> primaryKey => $id , $name => $value )), $options );
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-11-08 02:54:07 +00:00
* Saves model data ( based on white - list , if supplied ) to the database . By
2014-06-03 07:37:17 +00:00
* default , validation occurs before save . Passthrough method to _doSave () with
* transaction handling .
2008-05-30 11:40:08 +00:00
*
* @ param array $data Data to save .
2014-07-03 13:36:42 +00:00
* @ param bool | array $validate Either a boolean , or an array .
2009-09-03 15:59:57 +00:00
* If a boolean , indicates whether or not to validate before saving .
2013-04-07 13:23:32 +00:00
* If an array , can have following keys :
2013-04-07 17:43:03 +00:00
*
2014-06-03 07:37:17 +00:00
* - atomic : If true ( default ), will attempt to save the record in a single transaction .
2013-04-07 18:56:59 +00:00
* - 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'
2013-04-07 13:23:32 +00:00
* will enable only those callbacks .
2013-04-07 18:35:23 +00:00
* - `counterCache` : Boolean to control updating of counter caches ( if any )
2013-04-07 17:43:03 +00:00
*
2013-04-07 13:23:32 +00:00
* @ param array $fieldList List of fields to allow to be saved
2008-05-30 11:40:08 +00:00
* @ return mixed On success Model :: $data if its not empty or true , false on failure
2014-07-03 17:43:55 +00:00
* @ throws Exception
2014-07-12 02:56:36 +00:00
* @ throws PDOException
2014-11-30 21:45:40 +00:00
* @ triggers Model . beforeSave $this , array ( $options )
* @ triggers Model . afterSave $this , array ( $created , $options )
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / saving - your - data . html
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function save ( $data = null , $validate = true , $fieldList = array ()) {
2013-01-29 03:40:42 +00:00
$defaults = array (
'validate' => true , 'fieldList' => array (),
2014-06-03 07:37:17 +00:00
'callbacks' => true , 'counterCache' => true ,
'atomic' => true
2013-01-29 03:40:42 +00:00
);
2008-05-30 11:40:08 +00:00
if ( ! is_array ( $validate )) {
2014-04-07 23:25:14 +00:00
$options = compact ( 'validate' , 'fieldList' ) + $defaults ;
2008-05-30 11:40:08 +00:00
} else {
2014-04-07 23:25:14 +00:00
$options = $validate + $defaults ;
2008-05-30 11:40:08 +00:00
}
2014-07-03 17:43:55 +00:00
2014-06-03 07:37:17 +00:00
if ( ! $options [ 'atomic' ]) {
return $this -> _doSave ( $data , $options );
}
$db = $this -> getDataSource ();
$transactionBegun = $db -> begin ();
try {
$success = $this -> _doSave ( $data , $options );
if ( $transactionBegun ) {
if ( $success ) {
$db -> commit ();
} else {
$db -> rollback ();
}
}
return $success ;
} catch ( Exception $e ) {
if ( $transactionBegun ) {
$db -> rollback ();
}
throw $e ;
}
}
/**
* Saves model data ( based on white - list , if supplied ) to the database . By
* default , validation occurs before save .
*
* @ param array $data Data to save .
* @ param array $options 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 .
* - `counterCache` : Boolean to control updating of counter caches ( if any )
*
* @ return mixed On success Model :: $data if its not empty or true , false on failure
2014-07-21 12:01:43 +00:00
* @ throws PDOException
2014-06-03 07:37:17 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / saving - your - data . html
*/
protected function _doSave ( $data = null , $options = array ()) {
$_whitelist = $this -> whitelist ;
$fields = array ();
2008-05-30 11:40:08 +00:00
if ( ! empty ( $options [ 'fieldList' ])) {
2011-12-22 20:37:48 +00:00
if ( ! empty ( $options [ 'fieldList' ][ $this -> alias ]) && is_array ( $options [ 'fieldList' ][ $this -> alias ])) {
$this -> whitelist = $options [ 'fieldList' ][ $this -> alias ];
2013-08-02 21:19:41 +00:00
} elseif ( Hash :: dimensions ( $options [ 'fieldList' ]) < 2 ) {
$this -> whitelist = $options [ 'fieldList' ];
2011-12-22 20:37:48 +00:00
}
2008-05-30 11:40:08 +00:00
} elseif ( $options [ 'fieldList' ] === null ) {
$this -> whitelist = array ();
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
$this -> set ( $data );
if ( empty ( $this -> data ) && ! $this -> hasField ( array ( 'created' , 'updated' , 'modified' ))) {
2013-02-26 01:57:39 +00:00
$this -> whitelist = $_whitelist ;
2008-05-30 11:40:08 +00:00
return false ;
}
foreach ( array ( 'created' , 'updated' , 'modified' ) as $field ) {
2008-09-04 01:00:08 +00:00
$keyPresentAndEmpty = (
isset ( $this -> data [ $this -> alias ]) &&
array_key_exists ( $field , $this -> data [ $this -> alias ]) &&
$this -> data [ $this -> alias ][ $field ] === null
);
2013-09-01 19:09:14 +00:00
2008-09-04 01:00:08 +00:00
if ( $keyPresentAndEmpty ) {
2008-05-30 11:40:08 +00:00
unset ( $this -> data [ $this -> alias ][ $field ]);
}
}
2008-06-15 02:58:23 +00:00
2010-01-14 18:47:38 +00:00
$exists = $this -> exists ();
2008-05-30 11:40:08 +00:00
$dateFields = array ( 'modified' , 'updated' );
2010-01-14 18:47:38 +00:00
if ( ! $exists ) {
2008-05-30 11:40:08 +00:00
$dateFields [] = 'created' ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( isset ( $this -> data [ $this -> alias ])) {
$fields = array_keys ( $this -> data [ $this -> alias ]);
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( $options [ 'validate' ] && ! $this -> validates ( $options )) {
$this -> whitelist = $_whitelist ;
return false ;
}
2010-07-15 03:49:38 +00:00
$db = $this -> getDataSource ();
2013-06-11 19:19:59 +00:00
$now = time ();
2008-09-04 01:00:08 +00:00
2008-05-30 11:40:08 +00:00
foreach ( $dateFields as $updateCol ) {
2013-10-24 01:38:03 +00:00
if ( in_array ( $updateCol , $fields ) || ! $this -> hasField ( $updateCol )) {
continue ;
}
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
$default = array ( 'formatter' => 'date' );
$colType = array_merge ( $default , $db -> columns [ $this -> getColumnType ( $updateCol )]);
$time = $now ;
if ( array_key_exists ( 'format' , $colType )) {
$time = call_user_func ( $colType [ 'formatter' ], $colType [ 'format' ]);
}
if ( ! empty ( $this -> whitelist )) {
$this -> whitelist [] = $updateCol ;
2008-05-30 11:40:08 +00:00
}
2013-10-24 01:38:03 +00:00
$this -> set ( $updateCol , $time );
2008-05-30 11:40:08 +00:00
}
2008-06-20 20:17:23 +00:00
if ( $options [ 'callbacks' ] === true || $options [ 'callbacks' ] === 'before' ) {
2011-12-26 17:36:48 +00:00
$event = new CakeEvent ( 'Model.beforeSave' , $this , array ( $options ));
list ( $event -> break , $event -> breakOn ) = array ( true , array ( false , null ));
$this -> getEventManager () -> dispatch ( $event );
if ( ! $event -> result ) {
2008-05-30 11:40:08 +00:00
$this -> whitelist = $_whitelist ;
return false ;
}
}
2010-05-12 02:40:56 +00:00
if ( empty ( $this -> data [ $this -> alias ][ $this -> primaryKey ])) {
2008-05-30 11:40:08 +00:00
unset ( $this -> data [ $this -> alias ][ $this -> primaryKey ]);
}
2014-05-28 16:17:16 +00:00
$joined = $fields = $values = array ();
2008-05-30 11:40:08 +00:00
foreach ( $this -> data as $n => $v ) {
if ( isset ( $this -> hasAndBelongsToMany [ $n ])) {
if ( isset ( $v [ $n ])) {
$v = $v [ $n ];
}
$joined [ $n ] = $v ;
2013-10-24 01:38:03 +00:00
} elseif ( $n === $this -> alias ) {
foreach ( array ( 'created' , 'updated' , 'modified' ) as $field ) {
if ( array_key_exists ( $field , $v ) && empty ( $v [ $field ])) {
unset ( $v [ $field ]);
2008-05-30 11:40:08 +00:00
}
2013-10-24 01:38:03 +00:00
}
2008-05-30 11:40:08 +00:00
2013-10-24 01:38:03 +00:00
foreach ( $v as $x => $y ) {
if ( $this -> hasField ( $x ) && ( empty ( $this -> whitelist ) || in_array ( $x , $this -> whitelist ))) {
list ( $fields [], $values []) = array ( $x , $y );
2008-05-30 11:40:08 +00:00
}
}
}
}
2013-09-01 19:09:14 +00:00
2014-05-28 21:53:47 +00:00
if ( empty ( $fields ) && empty ( $joined )) {
$this -> whitelist = $_whitelist ;
return false ;
}
2008-05-30 11:40:08 +00:00
$count = count ( $fields );
2010-01-14 18:47:38 +00:00
if ( ! $exists && $count > 0 ) {
2008-05-30 11:40:08 +00:00
$this -> id = false ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
$success = true ;
$created = false ;
if ( $count > 0 ) {
2008-12-17 04:13:45 +00:00
$cache = $this -> _prepareUpdateFields ( array_combine ( $fields , $values ));
2008-05-30 11:40:08 +00:00
if ( ! empty ( $this -> id )) {
2014-07-12 02:56:36 +00:00
$this -> __safeUpdateMode = true ;
try {
$success = ( bool ) $db -> update ( $this , $fields , $values );
} catch ( Exception $e ) {
$this -> __safeUpdateMode = false ;
throw $e ;
}
$this -> __safeUpdateMode = false ;
2008-05-30 11:40:08 +00:00
} else {
2012-12-08 13:10:12 +00:00
if ( empty ( $this -> data [ $this -> alias ][ $this -> primaryKey ]) && $this -> _isUUIDField ( $this -> primaryKey )) {
2010-03-16 03:36:20 +00:00
if ( array_key_exists ( $this -> primaryKey , $this -> data [ $this -> alias ])) {
$j = array_search ( $this -> primaryKey , $fields );
$values [ $j ] = String :: uuid ();
} else {
list ( $fields [], $values []) = array ( $this -> primaryKey , String :: uuid ());
2008-05-30 11:40:08 +00:00
}
}
if ( ! $db -> create ( $this , $fields , $values )) {
2012-12-03 15:30:03 +00:00
$success = false ;
2008-05-30 11:40:08 +00:00
} else {
$created = true ;
}
}
2013-01-29 03:40:42 +00:00
if ( $success && $options [ 'counterCache' ] && ! empty ( $this -> belongsTo )) {
2008-12-17 04:13:45 +00:00
$this -> updateCounterCache ( $cache , $created );
}
2008-05-30 11:40:08 +00:00
}
2014-05-28 21:53:47 +00:00
if ( $success && ! empty ( $joined )) {
$this -> _saveMulti ( $joined , $this -> id , $db );
2012-12-16 18:18:59 +00:00
}
2014-05-28 21:53:47 +00:00
$this -> whitelist = $_whitelist ;
2013-09-01 19:09:14 +00:00
2014-05-28 21:53:47 +00:00
if ( ! $success ) {
return $success ;
}
2013-09-01 19:09:14 +00:00
2014-05-28 21:53:47 +00:00
if ( $count > 0 ) {
if ( $created ) {
$this -> data [ $this -> alias ][ $this -> primaryKey ] = $this -> id ;
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2014-05-28 21:53:47 +00:00
if ( $options [ 'callbacks' ] === true || $options [ 'callbacks' ] === 'after' ) {
$event = new CakeEvent ( 'Model.afterSave' , $this , array ( $created , $options ));
$this -> getEventManager () -> dispatch ( $event );
}
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2014-05-29 00:36:13 +00:00
if ( ! empty ( $this -> data )) {
$success = $this -> data ;
}
2014-05-28 21:53:47 +00:00
$this -> _clearCache ();
$this -> validationErrors = array ();
$this -> data = false ;
2008-05-30 11:40:08 +00:00
return $success ;
}
2009-07-24 19:18:37 +00:00
2012-12-04 02:29:06 +00:00
/**
* Check if the passed in field is a UUID field
*
* @ param string $field the field to check
2014-07-03 13:36:42 +00:00
* @ return bool
2012-12-04 02:29:06 +00:00
*/
2012-12-08 13:10:12 +00:00
protected function _isUUIDField ( $field ) {
2012-12-04 02:29:06 +00:00
$field = $this -> schema ( $field );
return $field [ 'length' ] == 36 && in_array ( $field [ 'type' ], array ( 'string' , 'binary' ));
}
2008-05-30 11:40:08 +00:00
/**
* Saves model hasAndBelongsToMany data to the database .
*
* @ param array $joined Data to save
2014-07-03 13:36:42 +00:00
* @ param int | string $id ID of record in this model
2014-06-04 18:58:55 +00:00
* @ param DataSource $db Datasource instance .
2011-07-30 22:38:57 +00:00
* @ return void
2008-05-30 11:40:08 +00:00
*/
2011-08-20 04:43:34 +00:00
protected function _saveMulti ( $joined , $id , $db ) {
2008-10-29 07:19:26 +00:00
foreach ( $joined as $assoc => $data ) {
2013-10-24 01:38:03 +00:00
if ( ! isset ( $this -> hasAndBelongsToMany [ $assoc ])) {
continue ;
}
2008-10-29 07:19:26 +00:00
2013-10-24 01:38:03 +00:00
$habtm = $this -> hasAndBelongsToMany [ $assoc ];
2011-11-05 11:15:51 +00:00
2013-10-24 01:38:03 +00:00
list ( $join ) = $this -> joinModel ( $habtm [ 'with' ]);
2008-10-23 13:29:32 +00:00
2013-10-24 01:38:03 +00:00
$Model = $this -> { $join };
2008-12-30 16:09:25 +00:00
2013-10-24 01:38:03 +00:00
if ( ! empty ( $habtm [ 'with' ])) {
$withModel = is_array ( $habtm [ 'with' ]) ? key ( $habtm [ 'with' ]) : $habtm [ 'with' ];
list (, $withModel ) = pluginSplit ( $withModel );
$dbMulti = $this -> { $withModel } -> getDataSource ();
} else {
$dbMulti = $db ;
}
2008-12-30 16:09:25 +00:00
2013-10-24 01:38:03 +00:00
$isUUID = ! empty ( $Model -> primaryKey ) && $Model -> _isUUIDField ( $Model -> primaryKey );
2008-10-29 07:19:26 +00:00
2013-10-24 01:38:03 +00:00
$newData = $newValues = $newJoins = array ();
$primaryAdded = false ;
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
$fields = array (
$dbMulti -> name ( $habtm [ 'foreignKey' ]),
$dbMulti -> name ( $habtm [ 'associationForeignKey' ])
);
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
$idField = $db -> name ( $Model -> primaryKey );
if ( $isUUID && ! in_array ( $idField , $fields )) {
$fields [] = $idField ;
$primaryAdded = true ;
}
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
foreach (( array ) $data as $row ) {
2014-04-29 12:19:33 +00:00
if (( is_string ( $row ) && ( strlen ( $row ) === 36 || strlen ( $row ) === 16 )) || is_numeric ( $row )) {
2013-10-24 01:38:03 +00:00
$newJoins [] = $row ;
$values = array ( $id , $row );
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
if ( $isUUID && $primaryAdded ) {
$values [] = String :: uuid ();
2008-10-29 07:19:26 +00:00
}
2013-10-24 01:38:03 +00:00
$newValues [ $row ] = $values ;
unset ( $values );
} elseif ( isset ( $row [ $habtm [ 'associationForeignKey' ]])) {
if ( ! empty ( $row [ $Model -> primaryKey ])) {
$newJoins [] = $row [ $habtm [ 'associationForeignKey' ]];
}
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
$newData [] = $row ;
} elseif ( isset ( $row [ $join ]) && isset ( $row [ $join ][ $habtm [ 'associationForeignKey' ]])) {
if ( ! empty ( $row [ $join ][ $Model -> primaryKey ])) {
$newJoins [] = $row [ $join ][ $habtm [ 'associationForeignKey' ]];
2010-03-16 03:14:23 +00:00
}
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
$newData [] = $row [ $join ];
}
}
2009-11-22 22:56:46 +00:00
2013-10-24 01:38:03 +00:00
$keepExisting = $habtm [ 'unique' ] === 'keepExisting' ;
if ( $habtm [ 'unique' ]) {
$conditions = array (
$join . '.' . $habtm [ 'foreignKey' ] => $id
);
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
if ( ! empty ( $habtm [ 'conditions' ])) {
$conditions = array_merge ( $conditions , ( array ) $habtm [ 'conditions' ]);
2008-05-30 11:40:08 +00:00
}
2013-10-24 01:38:03 +00:00
$associationForeignKey = $Model -> alias . '.' . $habtm [ 'associationForeignKey' ];
$links = $Model -> find ( 'all' , array (
'conditions' => $conditions ,
'recursive' => empty ( $habtm [ 'conditions' ]) ? - 1 : 0 ,
'fields' => $associationForeignKey ,
));
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
$oldLinks = Hash :: extract ( $links , " { n}. { $associationForeignKey } " );
if ( ! empty ( $oldLinks )) {
if ( $keepExisting && ! empty ( $newJoins )) {
$conditions [ $associationForeignKey ] = array_diff ( $oldLinks , $newJoins );
} else {
$conditions [ $associationForeignKey ] = $oldLinks ;
2009-01-16 04:09:44 +00:00
}
2013-10-24 01:38:03 +00:00
$dbMulti -> delete ( $Model , $conditions );
}
}
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
if ( ! empty ( $newData )) {
foreach ( $newData as $data ) {
$data [ $habtm [ 'foreignKey' ]] = $id ;
if ( empty ( $data [ $Model -> primaryKey ])) {
$Model -> create ();
2011-05-23 06:50:59 +00:00
}
2013-09-01 19:09:14 +00:00
2014-06-03 07:37:17 +00:00
$Model -> save ( $data , array ( 'atomic' => false ));
2013-10-24 01:38:03 +00:00
}
}
if ( ! empty ( $newValues )) {
if ( $keepExisting && ! empty ( $links )) {
foreach ( $links as $link ) {
$oldJoin = $link [ $join ][ $habtm [ 'associationForeignKey' ]];
if ( ! in_array ( $oldJoin , $newJoins )) {
$conditions [ $associationForeignKey ] = $oldJoin ;
$db -> delete ( $Model , $conditions );
} else {
unset ( $newValues [ $oldJoin ]);
}
2011-05-23 06:50:59 +00:00
}
2013-10-24 01:38:03 +00:00
$newValues = array_values ( $newValues );
}
if ( ! empty ( $newValues )) {
$dbMulti -> insertMulti ( $Model , $fields , $newValues );
2008-05-30 11:40:08 +00:00
}
}
}
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* Updates the counter cache of belongsTo associations after a save or delete operation
*
* @ param array $keys Optional foreign key data , defaults to the information $this -> data
2014-07-03 13:36:42 +00:00
* @ param bool $created True if a new record was created , otherwise only associations with
2009-10-06 01:27:34 +00:00
* 'counterScope' defined get updated
2008-05-30 11:40:08 +00:00
* @ return void
*/
2010-04-05 03:19:38 +00:00
public function updateCounterCache ( $keys = array (), $created = false ) {
2014-01-26 03:15:47 +00:00
if ( empty ( $keys ) && isset ( $this -> data [ $this -> alias ])) {
$keys = $this -> data [ $this -> alias ];
}
2008-12-17 04:13:45 +00:00
$keys [ 'old' ] = isset ( $keys [ 'old' ]) ? $keys [ 'old' ] : array ();
2008-05-30 11:40:08 +00:00
foreach ( $this -> belongsTo as $parent => $assoc ) {
2013-10-24 01:38:03 +00:00
if ( empty ( $assoc [ 'counterCache' ])) {
continue ;
}
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
$Model = $this -> { $parent };
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
if ( ! is_array ( $assoc [ 'counterCache' ])) {
if ( isset ( $assoc [ 'counterScope' ])) {
$assoc [ 'counterCache' ] = array ( $assoc [ 'counterCache' ] => $assoc [ 'counterScope' ]);
} else {
$assoc [ 'counterCache' ] = array ( $assoc [ 'counterCache' ] => array ());
}
}
2008-12-17 04:13:45 +00:00
2013-10-24 01:38:03 +00:00
$foreignKey = $assoc [ 'foreignKey' ];
$fkQuoted = $this -> escapeField ( $assoc [ 'foreignKey' ]);
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
foreach ( $assoc [ 'counterCache' ] as $field => $conditions ) {
if ( ! is_string ( $field )) {
$field = Inflector :: underscore ( $this -> alias ) . '_count' ;
}
2008-12-17 04:13:45 +00:00
2013-10-24 01:38:03 +00:00
if ( ! $Model -> hasField ( $field )) {
continue ;
}
2011-08-17 12:40:32 +00:00
2013-10-24 01:38:03 +00:00
if ( $conditions === true ) {
$conditions = array ();
} else {
$conditions = ( array ) $conditions ;
}
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
if ( ! array_key_exists ( $foreignKey , $keys )) {
$keys [ $foreignKey ] = $this -> field ( $foreignKey );
}
2011-08-17 12:40:32 +00:00
2013-10-24 01:38:03 +00:00
$recursive = ( empty ( $conditions ) ? - 1 : 0 );
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
if ( isset ( $keys [ 'old' ][ $foreignKey ]) && $keys [ 'old' ][ $foreignKey ] != $keys [ $foreignKey ]) {
$conditions [ $fkQuoted ] = $keys [ 'old' ][ $foreignKey ];
2014-09-10 14:29:23 +00:00
$count = ( int ) $this -> find ( 'count' , compact ( 'conditions' , 'recursive' ));
2011-08-17 12:40:32 +00:00
2013-10-24 01:38:03 +00:00
$Model -> updateAll (
2011-08-17 12:40:32 +00:00
array ( $field => $count ),
2013-10-24 01:38:03 +00:00
array ( $Model -> escapeField () => $keys [ 'old' ][ $foreignKey ])
2011-08-17 12:40:32 +00:00
);
}
2013-10-24 01:38:03 +00:00
$conditions [ $fkQuoted ] = $keys [ $foreignKey ];
if ( $recursive === 0 ) {
$conditions = array_merge ( $conditions , ( array ) $conditions );
}
2014-09-10 14:29:23 +00:00
$count = ( int ) $this -> find ( 'count' , compact ( 'conditions' , 'recursive' ));
2013-10-24 01:38:03 +00:00
$Model -> updateAll (
array ( $field => $count ),
array ( $Model -> escapeField () => $keys [ $foreignKey ])
);
2008-12-17 04:13:45 +00:00
}
}
}
2009-07-24 19:18:37 +00:00
2008-12-17 04:13:45 +00:00
/**
2013-04-07 18:56:59 +00:00
* Helper method for `Model::updateCounterCache()` . Checks the fields to be updated for
2008-12-17 04:13:45 +00:00
*
* @ param array $data The fields of the record that will be updated
* @ return array Returns updated foreign key values , along with an 'old' key containing the old
2010-03-06 03:07:39 +00:00
* values , or empty if no foreign keys are updated .
2008-12-17 04:13:45 +00:00
*/
2010-04-05 03:21:28 +00:00
protected function _prepareUpdateFields ( $data ) {
2008-12-17 04:13:45 +00:00
$foreignKeys = array ();
foreach ( $this -> belongsTo as $assoc => $info ) {
2014-05-11 23:17:18 +00:00
if ( isset ( $info [ 'counterCache' ]) && $info [ 'counterCache' ]) {
2008-12-17 04:13:45 +00:00
$foreignKeys [ $assoc ] = $info [ 'foreignKey' ];
2008-05-30 11:40:08 +00:00
}
}
2013-09-01 19:09:14 +00:00
2008-12-17 04:13:45 +00:00
$included = array_intersect ( $foreignKeys , array_keys ( $data ));
if ( empty ( $included ) || empty ( $this -> id )) {
return array ();
}
2013-09-01 19:09:14 +00:00
2008-12-17 04:13:45 +00:00
$old = $this -> find ( 'first' , array (
2012-02-16 16:22:45 +00:00
'conditions' => array ( $this -> alias . '.' . $this -> primaryKey => $this -> id ),
2008-12-17 04:13:45 +00:00
'fields' => array_values ( $included ),
'recursive' => - 1
));
2013-09-01 19:09:14 +00:00
2008-12-17 04:13:45 +00:00
return array_merge ( $data , array ( 'old' => $old [ $this -> alias ]));
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2011-12-02 05:58:09 +00:00
* Backwards compatible passthrough method for :
2011-07-25 07:39:03 +00:00
* saveMany (), validateMany (), saveAssociated () and validateAssociated ()
*
2008-10-31 19:05:30 +00:00
* Saves multiple individual records for a single model ; Also works with a single record , as well as
* all its associated records .
2008-05-30 11:40:08 +00:00
*
2009-09-03 15:59:57 +00:00
* #### Options
*
2013-04-07 18:56:59 +00:00
* - `validate` : Set to false to disable validation , true to validate each record before saving ,
2010-03-27 23:59:42 +00:00
* 'first' to validate * all * records before any are saved ( default ),
* or 'only' to only validate the records , but not save them .
2013-04-07 18:56:59 +00:00
* - `atomic` : If true ( default ), will attempt to save all records in a single transaction .
2009-09-03 15:59:57 +00:00
* Should be set to false if database / table does not support transactions .
2013-04-07 18:56:59 +00:00
* - `fieldList` : Equivalent to the $fieldList parameter in Model :: save () .
2012-02-12 16:38:03 +00:00
* It should be an associate array with model name as key and array of fields as value . Eg .
2015-01-09 12:47:25 +00:00
* `` `
2012-02-12 16:38:03 +00:00
* array (
* 'SomeModel' => array ( 'field' ),
* 'AssociatedModel' => array ( 'field' , 'otherfield' )
* )
2015-01-09 12:47:25 +00:00
* `` `
2013-04-10 02:09:56 +00:00
* - `deep` : See saveMany / saveAssociated
* - `callbacks` : See Model :: save ()
* - `counterCache` : See Model :: save ()
2009-09-03 15:59:57 +00:00
*
2011-07-25 07:39:03 +00:00
* @ param array $data Record data to save . This can be either a numerically - indexed array ( for saving multiple
2009-09-03 15:59:57 +00:00
* records of the same type ), or an array indexed by association name .
* @ param array $options Options to use when saving record data , See $options above .
2010-02-23 15:05:30 +00:00
* @ return mixed If atomic : True on success , or false on failure .
2010-03-06 03:07:39 +00:00
* Otherwise : array similar to the $data array passed , but values are set to true / false
* depending on whether each record saved successfully .
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / saving - your - data . html #model-saveassociated-array-data-null-array-options-array
* @ link http :// book . cakephp . org / 2.0 / en / models / saving - your - data . html #model-saveall-array-data-null-array-options-array
2008-05-30 11:40:08 +00:00
*/
2012-10-11 12:03:59 +00:00
public function saveAll ( $data = array (), $options = array ()) {
2014-04-07 23:25:14 +00:00
$options += array ( 'validate' => 'first' );
2012-03-11 01:57:18 +00:00
if ( Hash :: numeric ( array_keys ( $data ))) {
2011-07-25 07:39:03 +00:00
if ( $options [ 'validate' ] === 'only' ) {
return $this -> validateMany ( $data , $options );
}
2013-09-01 19:09:14 +00:00
2011-07-25 07:39:03 +00:00
return $this -> saveMany ( $data , $options );
}
2013-09-01 19:09:14 +00:00
2011-07-25 07:39:03 +00:00
if ( $options [ 'validate' ] === 'only' ) {
2012-02-13 00:00:28 +00:00
return $this -> validateAssociated ( $data , $options );
2011-07-25 07:39:03 +00:00
}
2013-09-01 19:09:14 +00:00
2011-07-25 07:39:03 +00:00
return $this -> saveAssociated ( $data , $options );
}
/**
* Saves multiple individual records for a single model
*
* #### Options
*
2013-04-07 18:56:59 +00:00
* - `validate` : Set to false to disable validation , true to validate each record before saving ,
2011-07-25 07:39:03 +00:00
* 'first' to validate * all * records before any are saved ( default ),
2013-04-07 18:56:59 +00:00
* - `atomic` : If true ( default ), will attempt to save all records in a single transaction .
2011-07-25 07:39:03 +00:00
* Should be set to false if database / table does not support transactions .
2013-04-07 18:56:59 +00:00
* - `fieldList` : Equivalent to the $fieldList parameter in Model :: save ()
* - `deep` : If set to true , all associated data will be saved as well .
2013-04-10 02:09:56 +00:00
* - `callbacks` : See Model :: save ()
* - `counterCache` : See Model :: save ()
2011-07-25 07:39:03 +00:00
*
* @ param array $data Record data to save . This should be a numerically - indexed array
* @ param array $options Options to use when saving record data , See $options above .
* @ return 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 .
2014-08-02 01:12:33 +00:00
* @ throws PDOException
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / saving - your - data . html #model-savemany-array-data-null-array-options-array
2011-07-25 07:39:03 +00:00
*/
public function saveMany ( $data = null , $options = array ()) {
2008-05-30 11:40:08 +00:00
if ( empty ( $data )) {
$data = $this -> data ;
}
2014-04-07 23:25:14 +00:00
$options += array ( 'validate' => 'first' , 'atomic' => true , 'deep' => false );
2008-05-30 11:40:08 +00:00
$this -> validationErrors = $validationErrors = array ();
2010-03-17 19:49:30 +00:00
if ( empty ( $data ) && $options [ 'validate' ] !== false ) {
$result = $this -> save ( $data , $options );
2012-04-16 20:46:58 +00:00
if ( ! $options [ 'atomic' ]) {
return array ( ! empty ( $result ));
}
2013-09-01 19:09:14 +00:00
2010-03-17 19:49:30 +00:00
return ! empty ( $result );
}
2011-07-25 07:39:03 +00:00
if ( $options [ 'validate' ] === 'first' ) {
$validates = $this -> validateMany ( $data , $options );
if (( ! $validates && $options [ 'atomic' ]) || ( ! $options [ 'atomic' ] && in_array ( false , $validates , true ))) {
return $validates ;
}
2012-04-16 07:45:44 +00:00
$options [ 'validate' ] = false ;
2011-07-25 07:39:03 +00:00
}
2014-08-03 13:34:11 +00:00
$transactionBegun = false ;
2011-07-25 07:39:03 +00:00
if ( $options [ 'atomic' ]) {
$db = $this -> getDataSource ();
2012-01-17 20:52:22 +00:00
$transactionBegun = $db -> begin ();
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
try {
$return = array ();
foreach ( $data as $key => $record ) {
$validates = $this -> create ( null ) !== null ;
$saved = false ;
if ( $validates ) {
if ( $options [ 'deep' ]) {
2014-08-09 03:28:06 +00:00
$saved = $this -> saveAssociated ( $record , array ( 'atomic' => false ) + $options );
2014-08-02 01:12:33 +00:00
} else {
2014-08-09 03:28:06 +00:00
$saved = $this -> save ( $record , array ( 'atomic' => false ) + $options );
2014-08-02 01:12:33 +00:00
}
}
$validates = ( $validates && ( $saved === true || ( is_array ( $saved ) && ! in_array ( false , $saved , true ))));
if ( ! $validates ) {
$validationErrors [ $key ] = $this -> validationErrors ;
2012-02-13 00:00:28 +00:00
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
if ( ! $options [ 'atomic' ]) {
$return [ $key ] = $validates ;
} elseif ( ! $validates ) {
break ;
}
2011-07-25 07:39:03 +00:00
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
$this -> validationErrors = $validationErrors ;
2011-07-25 07:39:03 +00:00
if ( ! $options [ 'atomic' ]) {
2014-08-02 01:12:33 +00:00
return $return ;
2011-07-25 07:39:03 +00:00
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
if ( $validates ) {
if ( $transactionBegun ) {
return $db -> commit () !== false ;
}
return true ;
}
2013-09-01 19:09:14 +00:00
2011-07-25 07:39:03 +00:00
if ( $transactionBegun ) {
2014-08-02 01:12:33 +00:00
$db -> rollback ();
2011-07-25 07:39:03 +00:00
}
2014-08-02 01:12:33 +00:00
return false ;
} catch ( Exception $e ) {
if ( $transactionBegun ) {
$db -> rollback ();
}
throw $e ;
2011-07-25 07:39:03 +00:00
}
}
2008-09-19 15:27:43 +00:00
2011-07-25 07:39:03 +00:00
/**
* Validates multiple individual records for a single model
*
* #### Options
*
2013-04-07 18:56:59 +00:00
* - `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 .
2011-07-25 07:39:03 +00:00
*
2012-05-10 04:35:30 +00:00
* 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
*
2014-06-04 18:58:55 +00:00
* @ param array & $data Record data to validate . This should be a numerically - indexed array
2011-07-25 07:39:03 +00:00
* @ param array $options Options to use when validating record data ( see above ), See also $options of validates () .
2014-07-03 13:36:42 +00:00
* @ return bool | array If atomic : True on success , or false on failure .
2011-07-25 07:39:03 +00:00
* Otherwise : array similar to the $data array passed , but values are set to true / false
* depending on whether each record validated successfully .
*/
2012-05-10 04:21:27 +00:00
public function validateMany ( & $data , $options = array ()) {
2012-04-28 23:50:22 +00:00
return $this -> validator () -> validateMany ( $data , $options );
2011-07-25 07:39:03 +00:00
}
2008-09-19 15:27:43 +00:00
2011-07-25 07:39:03 +00:00
/**
* Saves a single record , as well as all its directly associated records .
*
* #### Options
*
2013-04-07 18:56:59 +00:00
* - `validate` : Set to `false` to disable validation , `true` to validate each record before saving ,
2012-01-20 10:02:13 +00:00
* 'first' to validate * all * records before any are saved ( default ),
2013-04-07 18:56:59 +00:00
* - `atomic` : If true ( default ), will attempt to save all records in a single transaction .
2011-07-25 07:39:03 +00:00
* Should be set to false if database / table does not support transactions .
2013-04-07 18:56:59 +00:00
* - `fieldList` : Equivalent to the $fieldList parameter in Model :: save () .
2012-02-12 16:38:03 +00:00
* It should be an associate array with model name as key and array of fields as value . Eg .
2015-01-09 12:47:25 +00:00
* `` `
2012-02-12 16:38:03 +00:00
* array (
* 'SomeModel' => array ( 'field' ),
* 'AssociatedModel' => array ( 'field' , 'otherfield' )
* )
2015-01-09 12:47:25 +00:00
* `` `
2013-04-07 18:56:59 +00:00
* - `deep` : If set to true , not only directly associated data is saved , but deeper nested associated data as well .
2013-04-10 02:09:56 +00:00
* - `callbacks` : See Model :: save ()
* - `counterCache` : See Model :: save ()
2011-07-25 07:39:03 +00:00
*
* @ param array $data Record data to save . This should be an array indexed by association name .
* @ param array $options Options to use when saving record data , See $options above .
* @ return 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 .
2014-08-02 01:12:33 +00:00
* @ throws PDOException
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / saving - your - data . html #model-saveassociated-array-data-null-array-options-array
2011-07-25 07:39:03 +00:00
*/
public function saveAssociated ( $data = null , $options = array ()) {
if ( empty ( $data )) {
$data = $this -> data ;
}
2008-05-30 11:40:08 +00:00
2014-04-07 23:25:14 +00:00
$options += array ( 'validate' => 'first' , 'atomic' => true , 'deep' => false );
2011-07-25 07:39:03 +00:00
$this -> validationErrors = $validationErrors = array ();
if ( empty ( $data ) && $options [ 'validate' ] !== false ) {
$result = $this -> save ( $data , $options );
2012-04-16 20:46:58 +00:00
if ( ! $options [ 'atomic' ]) {
return array ( ! empty ( $result ));
}
2013-09-01 19:09:14 +00:00
2011-07-25 07:39:03 +00:00
return ! empty ( $result );
}
if ( $options [ 'validate' ] === 'first' ) {
$validates = $this -> validateAssociated ( $data , $options );
2012-10-20 19:12:05 +00:00
if (( ! $validates && $options [ 'atomic' ]) || ( ! $options [ 'atomic' ] && in_array ( false , Hash :: flatten ( $validates ), true ))) {
2011-07-25 07:39:03 +00:00
return $validates ;
2010-06-09 17:48:54 +00:00
}
2013-09-01 19:09:14 +00:00
2012-04-16 07:45:44 +00:00
$options [ 'validate' ] = false ;
2011-07-25 07:39:03 +00:00
}
2013-09-01 19:09:14 +00:00
2014-08-03 13:34:11 +00:00
$transactionBegun = false ;
2011-07-25 07:39:03 +00:00
if ( $options [ 'atomic' ]) {
$db = $this -> getDataSource ();
2012-01-17 20:52:22 +00:00
$transactionBegun = $db -> begin ();
2008-05-30 11:40:08 +00:00
}
2012-05-10 04:21:27 +00:00
2014-08-02 01:12:33 +00:00
try {
$associations = $this -> getAssociated ();
$return = array ();
$validates = true ;
foreach ( $data as $association => $values ) {
$isEmpty = empty ( $values ) || ( isset ( $values [ $association ]) && empty ( $values [ $association ]));
if ( $isEmpty || ! isset ( $associations [ $association ]) || $associations [ $association ] !== 'belongsTo' ) {
continue ;
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
$Model = $this -> { $association };
2013-10-24 01:38:03 +00:00
2014-08-02 01:12:33 +00:00
$validates = $Model -> create ( null ) !== null ;
$saved = false ;
if ( $validates ) {
if ( $options [ 'deep' ]) {
$saved = $Model -> saveAssociated ( $values , array ( 'atomic' => false ) + $options );
} else {
$saved = $Model -> save ( $values , array ( 'atomic' => false ) + $options );
}
$validates = ( $saved === true || ( is_array ( $saved ) && ! in_array ( false , $saved , true )));
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
if ( $validates ) {
$key = $this -> belongsTo [ $association ][ 'foreignKey' ];
if ( isset ( $data [ $this -> alias ])) {
$data [ $this -> alias ][ $key ] = $Model -> id ;
} else {
$data = array_merge ( array ( $key => $Model -> id ), $data , array ( $key => $Model -> id ));
}
$options = $this -> _addToWhiteList ( $key , $options );
2013-10-24 01:38:03 +00:00
} else {
2014-08-02 01:12:33 +00:00
$validationErrors [ $association ] = $Model -> validationErrors ;
2013-10-24 01:38:03 +00:00
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
$return [ $association ] = $validates ;
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2014-08-09 03:28:06 +00:00
if ( $validates && ! ( $this -> create ( null ) !== null && $this -> save ( $data , array ( 'atomic' => false ) + $options ))) {
2014-08-02 01:12:33 +00:00
$validationErrors [ $this -> alias ] = $this -> validationErrors ;
$validates = false ;
2013-10-24 01:38:03 +00:00
}
2014-08-02 01:12:33 +00:00
$return [ $this -> alias ] = $validates ;
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
foreach ( $data as $association => $values ) {
if ( ! $validates ) {
break ;
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
$isEmpty = empty ( $values ) || ( isset ( $values [ $association ]) && empty ( $values [ $association ]));
if ( $isEmpty || ! isset ( $associations [ $association ])) {
continue ;
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
$Model = $this -> { $association };
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
$type = $associations [ $association ];
$key = $this -> { $type }[ $association ][ 'foreignKey' ];
switch ( $type ) {
case 'hasOne' :
if ( isset ( $values [ $association ])) {
$values [ $association ][ $key ] = $this -> id ;
2013-10-24 01:38:03 +00:00
} else {
2014-08-02 01:12:33 +00:00
$values = array_merge ( array ( $key => $this -> id ), $values , array ( $key => $this -> id ));
2011-07-25 07:39:03 +00:00
}
2013-10-24 01:38:03 +00:00
2014-08-02 01:12:33 +00:00
$validates = $Model -> create ( null ) !== null ;
$saved = false ;
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
if ( $validates ) {
$options = $Model -> _addToWhiteList ( $key , $options );
if ( $options [ 'deep' ]) {
$saved = $Model -> saveAssociated ( $values , array ( 'atomic' => false ) + $options );
} else {
$saved = $Model -> save ( $values , $options );
}
2011-07-25 07:39:03 +00:00
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
$validates = ( $validates && ( $saved === true || ( is_array ( $saved ) && ! in_array ( false , $saved , true ))));
if ( ! $validates ) {
$validationErrors [ $association ] = $Model -> validationErrors ;
}
2013-10-24 01:38:03 +00:00
2014-08-02 01:12:33 +00:00
$return [ $association ] = $validates ;
break ;
case 'hasMany' :
foreach ( $values as $i => $value ) {
if ( isset ( $values [ $i ][ $association ])) {
$values [ $i ][ $association ][ $key ] = $this -> id ;
} else {
$values [ $i ] = array_merge ( array ( $key => $this -> id ), $value , array ( $key => $this -> id ));
}
}
$options = $Model -> _addToWhiteList ( $key , $options );
$_return = $Model -> saveMany ( $values , array ( 'atomic' => false ) + $options );
if ( in_array ( false , $_return , true )) {
$validationErrors [ $association ] = $Model -> validationErrors ;
$validates = false ;
}
$return [ $association ] = $_return ;
break ;
}
2008-05-30 11:40:08 +00:00
}
2014-08-02 01:12:33 +00:00
$this -> validationErrors = $validationErrors ;
2008-06-27 06:07:00 +00:00
2014-08-02 01:12:33 +00:00
if ( isset ( $validationErrors [ $this -> alias ])) {
$this -> validationErrors = $validationErrors [ $this -> alias ];
unset ( $validationErrors [ $this -> alias ]);
$this -> validationErrors = array_merge ( $this -> validationErrors , $validationErrors );
}
2008-05-30 11:40:08 +00:00
2014-08-02 01:12:33 +00:00
if ( ! $options [ 'atomic' ]) {
return $return ;
2010-09-29 03:37:28 +00:00
}
2014-08-02 01:12:33 +00:00
if ( $validates ) {
if ( $transactionBegun ) {
return $db -> commit () !== false ;
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
return true ;
}
2013-09-01 19:09:14 +00:00
2014-08-02 01:12:33 +00:00
if ( $transactionBegun ) {
$db -> rollback ();
}
return false ;
} catch ( Exception $e ) {
if ( $transactionBegun ) {
$db -> rollback ();
}
throw $e ;
}
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2012-11-02 09:56:49 +00:00
/**
* Helper method for saveAll () and friends , to add foreign key to fieldlist
*
* @ param string $key fieldname to be added to list
2014-06-04 18:58:55 +00:00
* @ param array $options Options list
2014-07-03 13:36:42 +00:00
* @ return array options
2012-11-02 09:56:49 +00:00
*/
protected function _addToWhiteList ( $key , $options ) {
if ( empty ( $options [ 'fieldList' ]) && $this -> whitelist && ! in_array ( $key , $this -> whitelist )) {
$options [ 'fieldList' ][ $this -> alias ] = $this -> whitelist ;
$options [ 'fieldList' ][ $this -> alias ][] = $key ;
return $options ;
}
2013-09-01 19:09:14 +00:00
2012-11-02 09:56:49 +00:00
if ( ! empty ( $options [ 'fieldList' ][ $this -> alias ]) && is_array ( $options [ 'fieldList' ][ $this -> alias ])) {
$options [ 'fieldList' ][ $this -> alias ][] = $key ;
return $options ;
}
2013-09-01 19:09:14 +00:00
2013-10-24 01:38:03 +00:00
if ( ! empty ( $options [ 'fieldList' ]) && is_array ( $options [ 'fieldList' ]) && Hash :: dimensions ( $options [ 'fieldList' ]) < 2 ) {
2012-11-02 09:56:49 +00:00
$options [ 'fieldList' ][] = $key ;
}
2013-09-01 19:09:14 +00:00
2012-11-02 09:56:49 +00:00
return $options ;
}
2008-05-30 11:40:08 +00:00
/**
2011-07-25 07:39:03 +00:00
* Validates a single record , as well as all its directly associated records .
2008-05-30 11:40:08 +00:00
*
2011-07-25 07:39:03 +00:00
* #### Options
*
2013-04-07 18:56:59 +00:00
* - `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 .
2011-07-25 07:39:03 +00:00
*
2012-05-10 04:35:30 +00:00
* 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
*
2014-06-04 18:58:55 +00:00
* @ param array & $data Record data to validate . This should be an array indexed by association name .
2011-07-30 22:38:57 +00:00
* @ param array $options Options to use when validating record data ( see above ), See also $options of validates () .
2014-07-03 13:36:42 +00:00
* @ return array | bool If atomic : True on success , or false on failure .
2011-07-25 07:39:03 +00:00
* Otherwise : array similar to the $data array passed , but values are set to true / false
* depending on whether each record validated successfully .
2008-05-30 11:40:08 +00:00
*/
2012-05-10 04:21:27 +00:00
public function validateAssociated ( & $data , $options = array ()) {
2012-05-11 03:06:55 +00:00
return $this -> validator () -> validateAssociated ( $data , $options );
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Updates multiple model records based on a set of conditions .
2008-05-30 11:40:08 +00:00
*
2008-07-31 15:38:23 +00:00
* @ param array $fields Set of fields and values , indexed by fields .
2009-09-03 15:59:57 +00:00
* Fields are treated as SQL snippets , to insert literal values manually escape your data .
2008-05-30 11:40:08 +00:00
* @ param mixed $conditions Conditions to match , true for all records
2014-07-03 13:36:42 +00:00
* @ return bool True on success , false on failure
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / saving - your - data . html #model-updateall-array-fields-array-conditions
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function updateAll ( $fields , $conditions = true ) {
2010-07-15 03:49:38 +00:00
return $this -> getDataSource () -> update ( $this , $fields , null , $conditions );
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Removes record for given ID . If no ID is given , the current ID is used . Returns true on success .
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ param int | string $id ID of record to delete
* @ param bool $cascade Set to true to delete records that depend on this record
* @ return bool True on success
2014-11-30 21:45:40 +00:00
* @ triggers Model . beforeDelete $this , array ( $cascade )
2014-11-30 21:50:11 +00:00
* @ triggers Model . afterDelete $this
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / deleting - data . html
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function delete ( $id = null , $cascade = true ) {
2008-05-30 11:40:08 +00:00
if ( ! empty ( $id )) {
$this -> id = $id ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
$id = $this -> id ;
2011-12-26 17:36:48 +00:00
$event = new CakeEvent ( 'Model.beforeDelete' , $this , array ( $cascade ));
list ( $event -> break , $event -> breakOn ) = array ( true , array ( false , null ));
$this -> getEventManager () -> dispatch ( $event );
2012-12-03 15:30:03 +00:00
if ( $event -> isStopped ()) {
return false ;
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( ! $this -> exists ()) {
return false ;
}
2010-09-30 03:31:41 +00:00
2012-12-03 15:30:03 +00:00
$this -> _deleteDependent ( $id , $cascade );
$this -> _deleteLinks ( $id );
$this -> id = $id ;
2008-05-30 11:40:08 +00:00
2012-12-03 15:30:03 +00:00
if ( ! empty ( $this -> belongsTo )) {
foreach ( $this -> belongsTo as $assoc ) {
if ( empty ( $assoc [ 'counterCache' ])) {
continue ;
2012-06-19 13:53:39 +00:00
}
2008-05-30 11:40:08 +00:00
2012-12-03 15:30:03 +00:00
$keys = $this -> find ( 'first' , array (
'fields' => $this -> _collectForeignKeys (),
'conditions' => array ( $this -> alias . '.' . $this -> primaryKey => $id ),
'recursive' => - 1 ,
'callbacks' => false
));
break ;
2008-05-30 11:40:08 +00:00
}
}
2012-12-03 15:30:03 +00:00
if ( ! $this -> getDataSource () -> delete ( $this , array ( $this -> alias . '.' . $this -> primaryKey => $id ))) {
return false ;
}
if ( ! empty ( $keys [ $this -> alias ])) {
$this -> updateCounterCache ( $keys [ $this -> alias ]);
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
$this -> getEventManager () -> dispatch ( new CakeEvent ( 'Model.afterDelete' , $this ));
$this -> _clearCache ();
$this -> id = false ;
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
return true ;
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Cascades model deletes through associated hasMany and hasOne child records .
2008-05-30 11:40:08 +00:00
*
* @ param string $id ID of record that was deleted
2014-07-03 13:36:42 +00:00
* @ param bool $cascade Set to true to delete records that depend on this record
2008-09-25 16:49:56 +00:00
* @ return void
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:21:28 +00:00
protected function _deleteDependent ( $id , $cascade ) {
2012-12-03 15:30:03 +00:00
if ( $cascade !== true ) {
return ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( ! empty ( $this -> __backAssociation )) {
2013-05-29 11:25:39 +00:00
$savedAssociations = $this -> __backAssociation ;
2008-05-30 11:40:08 +00:00
$this -> __backAssociation = array ();
}
2011-11-05 20:15:57 +00:00
2012-12-03 15:30:03 +00:00
foreach ( array_merge ( $this -> hasMany , $this -> hasOne ) as $assoc => $data ) {
2012-12-05 10:54:30 +00:00
if ( $data [ 'dependent' ] !== true ) {
continue ;
}
2011-11-30 19:02:36 +00:00
2013-10-24 01:38:03 +00:00
$Model = $this -> { $assoc };
2012-12-05 10:54:30 +00:00
2013-10-24 01:38:03 +00:00
if ( $data [ 'foreignKey' ] === false && $data [ 'conditions' ] && in_array ( $this -> name , $Model -> getAssociated ( 'belongsTo' ))) {
$Model -> recursive = 0 ;
2012-12-05 10:54:30 +00:00
$conditions = array ( $this -> escapeField ( null , $this -> name ) => $id );
} else {
2013-10-24 01:38:03 +00:00
$Model -> recursive = - 1 ;
$conditions = array ( $Model -> escapeField ( $data [ 'foreignKey' ]) => $id );
2012-12-05 10:54:30 +00:00
if ( $data [ 'conditions' ]) {
$conditions = array_merge (( array ) $data [ 'conditions' ], $conditions );
2012-12-03 15:30:03 +00:00
}
2012-12-05 10:54:30 +00:00
}
2008-05-30 11:40:08 +00:00
2012-12-05 10:54:30 +00:00
if ( isset ( $data [ 'exclusive' ]) && $data [ 'exclusive' ]) {
2013-10-24 01:38:03 +00:00
$Model -> deleteAll ( $conditions );
2012-12-05 10:54:30 +00:00
} else {
2013-10-24 01:38:03 +00:00
$records = $Model -> find ( 'all' , array (
'conditions' => $conditions , 'fields' => $Model -> primaryKey
2012-12-05 10:54:30 +00:00
));
2011-11-05 20:15:57 +00:00
2012-12-05 10:54:30 +00:00
if ( ! empty ( $records )) {
foreach ( $records as $record ) {
2013-10-24 01:38:03 +00:00
$Model -> delete ( $record [ $Model -> alias ][ $Model -> primaryKey ]);
2008-05-30 11:40:08 +00:00
}
}
}
}
2013-09-01 19:09:14 +00:00
2013-05-29 11:25:39 +00:00
if ( isset ( $savedAssociations )) {
$this -> __backAssociation = $savedAssociations ;
2008-05-30 11:40:08 +00:00
}
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Cascades model deletes through HABTM join keys .
2008-05-30 11:40:08 +00:00
*
* @ param string $id ID of record that was deleted
2008-09-25 16:49:56 +00:00
* @ return void
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:21:28 +00:00
protected function _deleteLinks ( $id ) {
2012-09-05 22:22:30 +00:00
foreach ( $this -> hasAndBelongsToMany as $data ) {
2012-12-05 10:55:11 +00:00
list (, $joinModel ) = pluginSplit ( $data [ 'with' ]);
2013-10-24 01:38:03 +00:00
$Model = $this -> { $joinModel };
$records = $Model -> find ( 'all' , array (
'conditions' => array ( $Model -> escapeField ( $data [ 'foreignKey' ]) => $id ),
'fields' => $Model -> primaryKey ,
2011-08-03 22:10:43 +00:00
'recursive' => - 1 ,
'callbacks' => false
2008-05-30 11:40:08 +00:00
));
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( ! empty ( $records )) {
foreach ( $records as $record ) {
2013-10-24 01:38:03 +00:00
$Model -> delete ( $record [ $Model -> alias ][ $Model -> primaryKey ]);
2008-05-30 11:40:08 +00:00
}
}
}
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Deletes multiple model records based on a set of conditions .
2008-05-30 11:40:08 +00:00
*
* @ param mixed $conditions Conditions to match
2014-07-03 13:36:42 +00:00
* @ param bool $cascade Set to true to delete records that depend on this record
* @ param bool $callbacks Run callbacks
* @ return bool True on success , false on failure
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / deleting - data . html #deleteall
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function deleteAll ( $conditions , $cascade = true , $callbacks = false ) {
2008-05-30 11:40:08 +00:00
if ( empty ( $conditions )) {
return false ;
}
2013-09-01 19:09:14 +00:00
2010-07-15 03:49:38 +00:00
$db = $this -> getDataSource ();
2008-05-30 11:40:08 +00:00
if ( ! $cascade && ! $callbacks ) {
return $db -> delete ( $this , $conditions );
2012-12-03 15:30:03 +00:00
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
$ids = $this -> find ( 'all' , array_merge ( array (
2014-03-14 14:20:12 +00:00
'fields' => " { $this -> alias } . { $this -> primaryKey } " ,
2013-12-08 09:40:22 +00:00
'order' => false ,
2014-03-14 14:20:12 +00:00
'group' => " { $this -> alias } . { $this -> primaryKey } " ,
2012-12-03 15:30:03 +00:00
'recursive' => 0 ), compact ( 'conditions' ))
);
2013-09-01 19:09:14 +00:00
2013-01-27 02:16:26 +00:00
if ( $ids === false || $ids === null ) {
2012-12-03 15:30:03 +00:00
return false ;
}
2008-05-30 11:40:08 +00:00
2012-12-03 15:30:03 +00:00
$ids = Hash :: extract ( $ids , " { n}. { $this -> alias } . { $this -> primaryKey } " );
if ( empty ( $ids )) {
return true ;
}
if ( $callbacks ) {
$_id = $this -> id ;
$result = true ;
foreach ( $ids as $id ) {
$result = $result && $this -> delete ( $id , $cascade );
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
$this -> id = $_id ;
return $result ;
}
2008-05-30 11:40:08 +00:00
2012-12-03 15:30:03 +00:00
foreach ( $ids as $id ) {
$this -> _deleteLinks ( $id );
if ( $cascade ) {
$this -> _deleteDependent ( $id , $cascade );
2008-05-30 11:40:08 +00:00
}
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
return $db -> delete ( $this , array ( $this -> alias . '.' . $this -> primaryKey => $ids ));
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Collects foreign keys from associations .
2008-05-30 11:40:08 +00:00
*
2014-06-04 18:58:55 +00:00
* @ param string $type Association type .
2008-09-25 16:49:56 +00:00
* @ return array
2008-05-30 11:40:08 +00:00
*/
2011-08-20 04:43:34 +00:00
protected function _collectForeignKeys ( $type = 'belongsTo' ) {
2008-05-30 11:40:08 +00:00
$result = array ();
foreach ( $this -> { $type } as $assoc => $data ) {
if ( isset ( $data [ 'foreignKey' ]) && is_string ( $data [ 'foreignKey' ])) {
$result [ $assoc ] = $data [ 'foreignKey' ];
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return $result ;
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2012-02-23 06:12:08 +00:00
* Returns true if a record with particular ID exists .
2008-05-30 11:40:08 +00:00
*
2013-04-07 18:56:59 +00:00
* 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
2010-01-14 21:42:16 +00:00
* to ascertain the existence of the record in persistent storage .
*
2014-07-03 13:36:42 +00:00
* @ param int | string $id ID of record to check for existence
* @ return bool True if such a record exists
2008-05-30 11:40:08 +00:00
*/
2012-02-23 06:12:08 +00:00
public function exists ( $id = null ) {
if ( $id === null ) {
$id = $this -> getID ();
}
2013-09-01 19:09:14 +00:00
2012-02-23 06:12:08 +00:00
if ( $id === false ) {
2008-05-30 11:40:08 +00:00
return false ;
}
2013-09-01 19:09:14 +00:00
2012-12-10 16:40:12 +00:00
return ( bool ) $this -> find ( 'count' , array (
2012-12-05 10:55:11 +00:00
'conditions' => array (
$this -> alias . '.' . $this -> primaryKey => $id
),
'recursive' => - 1 ,
'callbacks' => false
));
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns true if a record that meets given conditions exists .
2008-05-30 11:40:08 +00:00
*
* @ param array $conditions SQL conditions array
2014-07-03 13:36:42 +00:00
* @ return bool True if such a record exists
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function hasAny ( $conditions = null ) {
2012-09-21 22:32:52 +00:00
return ( bool ) $this -> find ( 'count' , array ( 'conditions' => $conditions , 'recursive' => - 1 ));
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2010-07-28 01:25:31 +00:00
* Queries the datasource and returns a result set array .
2008-05-30 11:40:08 +00:00
*
2013-02-27 03:00:55 +00:00
* Used to perform find operations , where the first argument is type of find operation to perform
2011-12-16 06:52:07 +00:00
* ( all / first / count / neighbors / list / threaded ),
2013-10-24 11:05:32 +00:00
* second parameter options for finding ( indexed array , including : 'conditions' , 'limit' ,
2013-02-27 03:00:55 +00:00
* 'recursive' , 'page' , 'fields' , 'offset' , 'order' , 'callbacks' )
2008-05-30 11:40:08 +00:00
*
2009-11-12 04:17:23 +00:00
* Eg :
2015-01-09 12:47:25 +00:00
* `` `
2013-02-27 03:00:55 +00:00
* $model -> find ( 'all' , array (
* 'conditions' => array ( 'name' => 'Thomas Anderson' ),
* 'fields' => array ( 'name' , 'email' ),
* 'order' => 'field3 DESC' ,
* 'recursive' => 2 ,
* 'group' => 'type' ,
* 'callbacks' => false ,
2009-10-06 01:01:31 +00:00
* ));
2015-01-09 12:47:25 +00:00
* `` `
2008-05-30 11:40:08 +00:00
*
2010-07-28 01:25:31 +00:00
* In addition to the standard query keys above , you can provide Datasource , and behavior specific
2012-12-22 22:48:15 +00:00
* keys . For example , when using a SQL based datasource you can use the joins key to specify additional
2010-07-28 01:25:31 +00:00
* joins that should be part of the query .
*
2015-01-09 12:47:25 +00:00
* `` `
2013-02-27 03:00:55 +00:00
* $model -> find ( 'all' , array (
* 'conditions' => array ( 'name' => 'Thomas Anderson' ),
* 'joins' => array (
* array (
* 'alias' => 'Thought' ,
* 'table' => 'thoughts' ,
* 'type' => 'LEFT' ,
* 'conditions' => '`Thought`.`person_id` = `Person`.`id`'
* )
* )
2010-07-28 01:25:31 +00:00
* ));
2015-01-09 12:47:25 +00:00
* `` `
2010-07-28 01:25:31 +00:00
*
2013-02-27 03:00:55 +00:00
* ### 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
*
2010-07-28 01:25:31 +00:00
* Behaviors and find types can also define custom finder keys which are passed into find () .
2013-02-27 03:00:55 +00:00
* 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 .
2010-07-28 01:25:31 +00:00
*
2011-02-23 02:45:27 +00:00
* Specifying 'fields' for notation 'list' :
2009-10-06 01:01:31 +00:00
*
2013-02-27 03:00:55 +00:00
* - 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 .
2008-05-30 11:40:08 +00:00
*
2013-02-27 03:00:55 +00:00
* Note : find ( list ) + database views have issues with MySQL 5.0 . Try upgrading to MySQL 5.1 if you
* have issues with database views .
2012-10-25 20:32:32 +00:00
*
2013-02-27 03:00:55 +00:00
* Note : find ( count ) has its own return values .
2012-10-25 20:32:32 +00:00
*
2011-02-23 02:45:27 +00:00
* @ param string $type Type of find operation ( all / first / count / neighbors / list / threaded )
2011-07-12 21:31:07 +00:00
* @ param array $query Option fields ( conditions / fields / joins / limit / offset / order / page / group / callbacks )
2014-11-05 12:03:27 +00:00
* @ return array | null Array of records , or Null on failure .
2012-12-21 14:06:43 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / retrieving - your - data . html
2008-05-30 11:40:08 +00:00
*/
2011-02-23 02:45:27 +00:00
public function find ( $type = 'first' , $query = array ()) {
2008-05-30 11:40:08 +00:00
$this -> findQueryType = $type ;
$this -> id = $this -> getID ();
2011-07-12 21:31:07 +00:00
$query = $this -> buildQuery ( $type , $query );
2013-08-16 18:12:49 +00:00
if ( $query === null ) {
2011-07-12 21:31:07 +00:00
return null ;
}
2013-02-10 11:09:26 +00:00
return $this -> _readDataSource ( $type , $query );
2013-02-09 16:09:50 +00:00
}
/**
2013-02-10 11:09:26 +00:00
* 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 .
2013-08-08 01:56:58 +00:00
*
2015-01-09 12:47:25 +00:00
* `` `
2013-02-10 11:09:26 +00:00
* protected function _readDataSource ( $type , $query ) {
* $cacheName = md5 ( json_encode ( $query ));
* $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 ;
* }
2015-01-09 12:47:25 +00:00
* `` `
2013-08-08 01:56:58 +00:00
*
2013-02-10 11:09:26 +00:00
* @ param string $type Type of find operation ( all / first / count / neighbors / list / threaded )
* @ param array $query Option fields ( conditions / fields / joins / limit / offset / order / page / group / callbacks )
* @ return array
2013-02-09 16:09:50 +00:00
*/
2013-02-10 11:09:26 +00:00
protected function _readDataSource ( $type , $query ) {
2011-07-12 21:31:07 +00:00
$results = $this -> getDataSource () -> read ( $this , $query );
$this -> resetAssociations ();
if ( $query [ 'callbacks' ] === true || $query [ 'callbacks' ] === 'after' ) {
$results = $this -> _filterResults ( $results );
}
$this -> findQueryType = null ;
2012-10-25 20:32:32 +00:00
if ( $this -> findMethods [ $type ] === true ) {
return $this -> { '_find' . ucfirst ( $type )}( 'after' , $query , $results );
2011-07-12 21:31:07 +00:00
}
}
/**
* Builds the query array that is used by the data source to generate the query to fetch the data .
*
* @ param string $type Type of find operation ( all / first / count / neighbors / list / threaded )
* @ param array $query Option fields ( conditions / fields / joins / limit / offset / order / page / group / callbacks )
2014-11-05 12:03:27 +00:00
* @ return array | null Query array or null if it could not be build for some reasons
2014-11-30 21:45:40 +00:00
* @ triggers Model . beforeFind $this , array ( $query )
2011-07-12 21:31:07 +00:00
* @ see Model :: find ()
*/
public function buildQuery ( $type = 'first' , $query = array ()) {
2008-05-30 11:40:08 +00:00
$query = array_merge (
array (
2008-06-21 02:33:04 +00:00
'conditions' => null , 'fields' => null , 'joins' => array (), 'limit' => null ,
2011-07-11 22:54:24 +00:00
'offset' => null , 'order' => null , 'page' => 1 , 'group' => null , 'callbacks' => true ,
2008-05-30 11:40:08 +00:00
),
2008-06-19 17:06:50 +00:00
( array ) $query
2008-05-30 11:40:08 +00:00
);
2013-02-10 11:19:21 +00:00
if ( $this -> findMethods [ $type ] === true ) {
2012-12-03 15:30:03 +00:00
$query = $this -> { '_find' . ucfirst ( $type )}( 'before' , $query );
2008-05-30 11:40:08 +00:00
}
2014-09-10 14:29:23 +00:00
if ( ! is_numeric ( $query [ 'page' ]) || ( int ) $query [ 'page' ] < 1 ) {
2008-05-30 11:40:08 +00:00
$query [ 'page' ] = 1 ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( $query [ 'page' ] > 1 && ! empty ( $query [ 'limit' ])) {
$query [ 'offset' ] = ( $query [ 'page' ] - 1 ) * $query [ 'limit' ];
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( $query [ 'order' ] === null && $this -> order !== null ) {
$query [ 'order' ] = $this -> order ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
$query [ 'order' ] = array ( $query [ 'order' ]);
2008-06-21 02:33:04 +00:00
if ( $query [ 'callbacks' ] === true || $query [ 'callbacks' ] === 'before' ) {
2011-12-26 17:36:48 +00:00
$event = new CakeEvent ( 'Model.beforeFind' , $this , array ( $query ));
list ( $event -> break , $event -> breakOn , $event -> modParams ) = array ( true , array ( false , null ), 0 );
$this -> getEventManager () -> dispatch ( $event );
2013-09-01 19:09:14 +00:00
2011-12-26 17:36:48 +00:00
if ( $event -> isStopped ()) {
2008-06-21 02:33:04 +00:00
return null ;
}
2013-09-01 19:09:14 +00:00
2011-12-26 18:08:04 +00:00
$query = $event -> result === true ? $event -> data [ 0 ] : $event -> result ;
2008-05-30 11:40:08 +00:00
}
2011-07-31 01:03:56 +00:00
2011-07-12 21:31:07 +00:00
return $query ;
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2013-02-10 11:19:21 +00:00
/**
* Handles the before / after filter logic for find ( 'all' ) operations . Only called by Model :: find () .
*
* @ param string $state Either " before " or " after "
2014-06-04 18:58:55 +00:00
* @ param array $query Query .
* @ param array $results Results .
2013-02-10 11:19:21 +00:00
* @ return array
* @ see Model :: find ()
*/
protected function _findAll ( $state , $query , $results = array ()) {
if ( $state === 'before' ) {
return $query ;
}
2013-09-01 18:06:45 +00:00
return $results ;
2013-02-10 11:19:21 +00:00
}
2008-05-30 11:40:08 +00:00
/**
2012-12-22 22:48:15 +00:00
* Handles the before / after filter logic for find ( 'first' ) operations . Only called by Model :: find () .
2008-05-30 11:40:08 +00:00
*
* @ param string $state Either " before " or " after "
2014-06-04 18:58:55 +00:00
* @ param array $query Query .
* @ param array $results Results .
2008-05-30 11:40:08 +00:00
* @ return array
2008-10-31 19:05:30 +00:00
* @ see Model :: find ()
2008-05-30 11:40:08 +00:00
*/
2011-02-23 02:42:15 +00:00
protected function _findFirst ( $state , $query , $results = array ()) {
2011-02-23 02:47:27 +00:00
if ( $state === 'before' ) {
2008-05-30 11:40:08 +00:00
$query [ 'limit' ] = 1 ;
return $query ;
}
2013-09-01 18:06:45 +00:00
if ( empty ( $results [ 0 ])) {
return array ();
}
2013-09-01 19:09:14 +00:00
2013-09-01 18:06:45 +00:00
return $results [ 0 ];
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2012-12-22 22:48:15 +00:00
* Handles the before / after filter logic for find ( 'count' ) operations . Only called by Model :: find () .
2008-05-30 11:40:08 +00:00
*
* @ param string $state Either " before " or " after "
2014-06-04 18:58:55 +00:00
* @ param array $query Query .
* @ param array $results Results .
2014-07-03 13:36:42 +00:00
* @ return int The number of records found , or false
2008-10-31 19:05:30 +00:00
* @ see Model :: find ()
2008-05-30 11:40:08 +00:00
*/
2011-02-23 02:42:15 +00:00
protected function _findCount ( $state , $query , $results = array ()) {
2011-02-23 02:47:27 +00:00
if ( $state === 'before' ) {
2012-09-28 11:49:51 +00:00
if ( ! empty ( $query [ 'type' ]) && isset ( $this -> findMethods [ $query [ 'type' ]]) && $query [ 'type' ] !== 'count' ) {
2012-02-29 19:20:58 +00:00
$query [ 'operation' ] = 'count' ;
$query = $this -> { '_find' . ucfirst ( $query [ 'type' ])}( 'before' , $query );
}
2013-09-01 19:09:14 +00:00
2010-07-15 03:49:38 +00:00
$db = $this -> getDataSource ();
2012-02-05 17:54:20 +00:00
$query [ 'order' ] = false ;
2012-04-05 21:15:18 +00:00
if ( ! method_exists ( $db , 'calculate' )) {
2012-02-05 17:54:20 +00:00
return $query ;
}
2013-09-01 19:09:14 +00:00
2012-02-29 19:20:58 +00:00
if ( ! empty ( $query [ 'fields' ]) && is_array ( $query [ 'fields' ])) {
if ( ! preg_match ( '/^count/i' , current ( $query [ 'fields' ]))) {
unset ( $query [ 'fields' ]);
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( empty ( $query [ 'fields' ])) {
$query [ 'fields' ] = $db -> calculate ( $this , 'count' );
2012-04-05 21:15:18 +00:00
} elseif ( method_exists ( $db , 'expression' ) && is_string ( $query [ 'fields' ]) && ! preg_match ( '/count/i' , $query [ 'fields' ])) {
2008-10-01 15:27:29 +00:00
$query [ 'fields' ] = $db -> calculate ( $this , 'count' , array (
$db -> expression ( $query [ 'fields' ]), 'count'
));
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return $query ;
2013-09-01 18:06:45 +00:00
}
foreach ( array ( 0 , $this -> alias ) as $key ) {
if ( isset ( $results [ 0 ][ $key ][ 'count' ])) {
if ( $query [ 'group' ]) {
return count ( $results );
2011-08-14 01:59:21 +00:00
}
2013-09-01 19:09:14 +00:00
2014-09-10 14:29:23 +00:00
return ( int ) $results [ 0 ][ $key ][ 'count' ];
2008-05-30 11:40:08 +00:00
}
}
2013-09-01 19:09:14 +00:00
2013-09-01 18:06:45 +00:00
return false ;
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2012-12-22 22:48:15 +00:00
* Handles the before / after filter logic for find ( 'list' ) operations . Only called by Model :: find () .
2008-05-30 11:40:08 +00:00
*
* @ param string $state Either " before " or " after "
2014-06-04 18:58:55 +00:00
* @ param array $query Query .
* @ param array $results Results .
2008-05-30 11:40:08 +00:00
* @ return array Key / value pairs of primary keys / display field values of all records found
2008-10-31 19:05:30 +00:00
* @ see Model :: find ()
2008-05-30 11:40:08 +00:00
*/
2011-02-23 02:42:15 +00:00
protected function _findList ( $state , $query , $results = array ()) {
2011-02-23 02:47:27 +00:00
if ( $state === 'before' ) {
2008-05-30 11:40:08 +00:00
if ( empty ( $query [ 'fields' ])) {
$query [ 'fields' ] = array ( " { $this -> alias } . { $this -> primaryKey } " , " { $this -> alias } . { $this -> displayField } " );
$list = array ( " { n}. { $this -> alias } . { $this -> primaryKey } " , " { n}. { $this -> alias } . { $this -> displayField } " , null );
} else {
if ( ! is_array ( $query [ 'fields' ])) {
$query [ 'fields' ] = String :: tokenize ( $query [ 'fields' ]);
}
2008-06-10 17:27:12 +00:00
2011-02-23 02:47:27 +00:00
if ( count ( $query [ 'fields' ]) === 1 ) {
2008-06-10 17:27:12 +00:00
if ( strpos ( $query [ 'fields' ][ 0 ], '.' ) === false ) {
$query [ 'fields' ][ 0 ] = $this -> alias . '.' . $query [ 'fields' ][ 0 ];
}
2008-05-30 11:40:08 +00:00
$list = array ( " { n}. { $this -> alias } . { $this -> primaryKey } " , '{n}.' . $query [ 'fields' ][ 0 ], null );
$query [ 'fields' ] = array ( " { $this -> alias } . { $this -> primaryKey } " , $query [ 'fields' ][ 0 ]);
2011-02-23 02:47:27 +00:00
} elseif ( count ( $query [ 'fields' ]) === 3 ) {
2008-06-11 08:54:27 +00:00
for ( $i = 0 ; $i < 3 ; $i ++ ) {
2008-06-10 17:27:12 +00:00
if ( strpos ( $query [ 'fields' ][ $i ], '.' ) === false ) {
$query [ 'fields' ][ $i ] = $this -> alias . '.' . $query [ 'fields' ][ $i ];
}
}
2008-05-30 11:40:08 +00:00
$list = array ( '{n}.' . $query [ 'fields' ][ 0 ], '{n}.' . $query [ 'fields' ][ 1 ], '{n}.' . $query [ 'fields' ][ 2 ]);
} else {
2008-06-11 08:54:27 +00:00
for ( $i = 0 ; $i < 2 ; $i ++ ) {
2008-06-10 17:27:12 +00:00
if ( strpos ( $query [ 'fields' ][ $i ], '.' ) === false ) {
$query [ 'fields' ][ $i ] = $this -> alias . '.' . $query [ 'fields' ][ $i ];
}
}
2008-05-30 11:40:08 +00:00
$list = array ( '{n}.' . $query [ 'fields' ][ 0 ], '{n}.' . $query [ 'fields' ][ 1 ], null );
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( ! isset ( $query [ 'recursive' ]) || $query [ 'recursive' ] === null ) {
$query [ 'recursive' ] = - 1 ;
}
list ( $query [ 'list' ][ 'keyPath' ], $query [ 'list' ][ 'valuePath' ], $query [ 'list' ][ 'groupPath' ]) = $list ;
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return $query ;
}
2013-09-01 18:06:45 +00:00
if ( empty ( $results )) {
return array ();
}
2013-09-01 19:09:14 +00:00
2013-09-01 18:06:45 +00:00
return Hash :: combine ( $results , $query [ 'list' ][ 'keyPath' ], $query [ 'list' ][ 'valuePath' ], $query [ 'list' ][ 'groupPath' ]);
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-06-26 19:33:44 +00:00
/**
2008-10-31 19:05:30 +00:00
* Detects the previous field 's value, then uses logic to find the ' wrapping '
* rows and return them .
2008-06-26 19:42:07 +00:00
*
2008-06-26 19:33:44 +00:00
* @ param string $state Either " before " or " after "
2014-06-04 18:58:55 +00:00
* @ param array $query Query .
* @ param array $results Results .
2008-09-25 16:49:56 +00:00
* @ return array
2008-06-26 19:33:44 +00:00
*/
2010-04-05 03:21:28 +00:00
protected function _findNeighbors ( $state , $query , $results = array ()) {
2013-09-01 19:08:48 +00:00
extract ( $query );
2011-02-23 02:47:27 +00:00
if ( $state === 'before' ) {
2008-06-26 19:33:44 +00:00
$conditions = ( array ) $conditions ;
if ( isset ( $field ) && isset ( $value )) {
if ( strpos ( $field , '.' ) === false ) {
2008-06-26 19:42:07 +00:00
$field = $this -> alias . '.' . $field ;
}
2008-06-26 19:33:44 +00:00
} else {
$field = $this -> alias . '.' . $this -> primaryKey ;
$value = $this -> id ;
}
2013-09-01 19:09:14 +00:00
2012-03-05 03:49:38 +00:00
$query [ 'conditions' ] = array_merge ( $conditions , array ( $field . ' <' => $value ));
2008-06-26 19:33:44 +00:00
$query [ 'order' ] = $field . ' DESC' ;
$query [ 'limit' ] = 1 ;
$query [ 'field' ] = $field ;
$query [ 'value' ] = $value ;
2013-09-01 19:09:14 +00:00
2008-06-26 19:42:07 +00:00
return $query ;
2008-06-26 19:33:44 +00:00
}
2013-09-01 18:06:45 +00:00
unset ( $query [ 'conditions' ][ $field . ' <' ]);
$return = array ();
if ( isset ( $results [ 0 ])) {
$prevVal = Hash :: get ( $results [ 0 ], $field );
$query [ 'conditions' ][ $field . ' >=' ] = $prevVal ;
$query [ 'conditions' ][ $field . ' !=' ] = $value ;
$query [ 'limit' ] = 2 ;
} else {
$return [ 'prev' ] = null ;
$query [ 'conditions' ][ $field . ' >' ] = $value ;
$query [ 'limit' ] = 1 ;
}
2013-09-01 19:09:14 +00:00
2013-09-01 18:06:45 +00:00
$query [ 'order' ] = $field . ' ASC' ;
$neighbors = $this -> find ( 'all' , $query );
if ( ! array_key_exists ( 'prev' , $return )) {
$return [ 'prev' ] = isset ( $neighbors [ 0 ]) ? $neighbors [ 0 ] : null ;
}
2013-09-01 19:09:14 +00:00
2013-09-01 18:06:45 +00:00
if ( count ( $neighbors ) === 2 ) {
$return [ 'next' ] = $neighbors [ 1 ];
} elseif ( count ( $neighbors ) === 1 && ! $return [ 'prev' ]) {
$return [ 'next' ] = $neighbors [ 0 ];
} else {
$return [ 'next' ] = null ;
}
2013-09-01 19:09:14 +00:00
2013-09-01 18:06:45 +00:00
return $return ;
2008-06-26 19:33:44 +00:00
}
2009-05-01 21:05:46 +00:00
2008-06-26 19:33:44 +00:00
/**
2008-08-01 16:49:56 +00:00
* 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
*
2014-06-04 18:58:55 +00:00
* @ param string $state Either " before " or " after " .
* @ param array $query Query .
* @ param array $results Results .
2008-06-26 19:33:44 +00:00
* @ return array Threaded results
*/
2010-04-05 03:21:28 +00:00
protected function _findThreaded ( $state , $query , $results = array ()) {
2011-02-23 02:47:27 +00:00
if ( $state === 'before' ) {
2008-06-26 19:33:44 +00:00
return $query ;
}
2013-09-01 18:06:45 +00:00
$parent = 'parent_id' ;
if ( isset ( $query [ 'parent' ])) {
$parent = $query [ 'parent' ];
}
2013-09-01 19:09:14 +00:00
2013-09-01 18:06:45 +00:00
return Hash :: nest ( $results , array (
'idPath' => '{n}.' . $this -> alias . '.' . $this -> primaryKey ,
'parentPath' => '{n}.' . $this -> alias . '.' . $parent
));
2008-06-26 19:42:07 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2013-11-10 16:59:28 +00:00
* Passes query results through model and behavior afterFind () methods .
2008-05-30 11:40:08 +00:00
*
2011-07-30 22:38:57 +00:00
* @ param array $results Results to filter
2014-07-03 13:36:42 +00:00
* @ param bool $primary If this is the primary model results ( results from model where the find operation was performed )
2008-05-30 11:40:08 +00:00
* @ return array Set of filtered results
2014-11-30 21:45:40 +00:00
* @ triggers Model . afterFind $this , array ( $results , $primary )
2008-05-30 11:40:08 +00:00
*/
2011-02-25 16:26:14 +00:00
protected function _filterResults ( $results , $primary = true ) {
2011-12-26 17:36:48 +00:00
$event = new CakeEvent ( 'Model.afterFind' , $this , array ( $results , $primary ));
$event -> modParams = 0 ;
$this -> getEventManager () -> dispatch ( $event );
return $event -> result ;
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
* This resets the association arrays for the model back
2010-07-01 16:39:50 +00:00
* to those originally defined in the model . Normally called at the end
* of each call to Model :: find ()
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ return bool Success
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function resetAssociations () {
2008-05-30 11:40:08 +00:00
if ( ! empty ( $this -> __backAssociation )) {
2011-08-20 04:43:34 +00:00
foreach ( $this -> _associations as $type ) {
2008-05-30 11:40:08 +00:00
if ( isset ( $this -> __backAssociation [ $type ])) {
$this -> { $type } = $this -> __backAssociation [ $type ];
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
$this -> __backAssociation = array ();
}
2011-08-20 04:43:34 +00:00
foreach ( $this -> _associations as $type ) {
2008-05-30 11:40:08 +00:00
foreach ( $this -> { $type } as $key => $name ) {
2010-07-14 21:28:12 +00:00
if ( property_exists ( $this , $key ) && ! empty ( $this -> { $key } -> __backAssociation )) {
2008-05-30 11:40:08 +00:00
$this -> { $key } -> resetAssociations ();
}
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
$this -> __backAssociation = array ();
return true ;
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns false if any fields passed match any ( by default , all if $or = false ) of their matching values .
2008-05-30 11:40:08 +00:00
*
2014-10-10 02:49:17 +00:00
* Can be used as a validation method . When used as a validation method , the `$or` parameter
* contains an array of fields to be validated .
*
2008-05-30 11:40:08 +00:00
* @ param array $fields Field / value pairs to search ( if no values specified , they are pulled from $this -> data )
2014-10-10 02:49:17 +00:00
* @ param bool | array $or If false , all fields specified must match in order for a false return value
2014-07-03 13:36:42 +00:00
* @ return bool False if any records matching any fields are found
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function isUnique ( $fields , $or = true ) {
2014-10-10 02:49:17 +00:00
if ( is_array ( $or )) {
2014-10-13 21:59:31 +00:00
$isRule = (
array_key_exists ( 'rule' , $or ) &&
array_key_exists ( 'required' , $or ) &&
array_key_exists ( 'message' , $or )
);
if ( ! $isRule ) {
2014-10-13 12:42:46 +00:00
$args = func_get_args ();
$fields = $args [ 1 ];
$or = isset ( $args [ 2 ]) ? $args [ 2 ] : true ;
}
2014-10-10 02:49:17 +00:00
}
2008-05-30 11:40:08 +00:00
if ( ! is_array ( $fields )) {
$fields = func_get_args ();
2014-11-11 21:13:16 +00:00
$fieldCount = count ( $fields ) - 1 ;
if ( is_bool ( $fields [ $fieldCount ])) {
$or = $fields [ $fieldCount ];
unset ( $fields [ $fieldCount ]);
2008-05-30 11:40:08 +00:00
}
}
foreach ( $fields as $field => $value ) {
if ( is_numeric ( $field )) {
unset ( $fields [ $field ]);
$field = $value ;
2012-12-03 15:30:03 +00:00
$value = null ;
2008-05-30 11:40:08 +00:00
if ( isset ( $this -> data [ $this -> alias ][ $field ])) {
$value = $this -> data [ $this -> alias ][ $field ];
}
}
if ( strpos ( $field , '.' ) === false ) {
unset ( $fields [ $field ]);
$fields [ $this -> alias . '.' . $field ] = $value ;
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( $or ) {
$fields = array ( 'or' => $fields );
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( ! empty ( $this -> id )) {
2012-03-04 19:18:04 +00:00
$fields [ $this -> alias . '.' . $this -> primaryKey . ' !=' ] = $this -> id ;
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2012-09-14 17:42:25 +00:00
return ! $this -> find ( 'count' , array ( 'conditions' => $fields , 'recursive' => - 1 ));
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns a resultset for a given SQL statement . Custom SQL queries should be performed with this method .
2008-05-30 11:40:08 +00:00
*
2014-06-04 18:58:55 +00:00
* The method can options 2 nd and 3 rd parameters .
*
* - 2 nd param : Either a boolean to control query caching or an array of parameters
2013-04-11 01:43:25 +00:00
* for use with prepared statement placeholders .
2014-06-04 18:58:55 +00:00
* - 3 rd param : If 2 nd argument is provided , a boolean flag for enabling / disabled
* query caching .
*
* @ param string $sql SQL statement
2012-04-03 13:36:41 +00:00
* @ return mixed Resultset array or boolean indicating success / failure depending on the query executed
2011-10-15 17:04:31 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / retrieving - your - data . html #model-query
2008-05-30 11:40:08 +00:00
*/
2011-08-22 01:45:34 +00:00
public function query ( $sql ) {
2008-05-30 11:40:08 +00:00
$params = func_get_args ();
2010-07-15 03:49:38 +00:00
$db = $this -> getDataSource ();
2008-05-30 11:40:08 +00:00
return call_user_func_array ( array ( & $db , 'query' ), $params );
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2009-12-15 04:21:26 +00:00
* Returns true if all fields pass validation . Will validate hasAndBelongsToMany associations
2011-08-20 04:43:34 +00:00
* that use the 'with' key as well . Since _saveMulti is incapable of exiting a save operation .
2008-05-30 11:40:08 +00:00
*
2012-12-22 22:48:15 +00:00
* Will validate the currently set data . Use Model :: set () or Model :: create () to set the active data .
2009-12-03 05:53:31 +00:00
*
2012-02-17 12:51:20 +00:00
* @ param array $options An optional array of custom options to be made available in the beforeValidate callback
2014-07-03 13:36:42 +00:00
* @ return bool True if there are no errors
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function validates ( $options = array ()) {
2012-04-28 23:50:22 +00:00
return $this -> validator () -> validates ( $options );
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2013-09-16 14:13:58 +00:00
* Returns an array of fields that have failed the validation of the current model .
2013-09-16 16:04:29 +00:00
*
2013-09-16 14:13:58 +00:00
* Additionally it populates the validationErrors property of the model with the same array .
2008-05-30 11:40:08 +00:00
*
2013-10-24 11:05:32 +00:00
* @ param array | string $options An optional array of custom options to be made available in the beforeValidate callback
2013-09-16 16:04:29 +00:00
* @ return array Array of invalid fields and their error messages
2009-12-03 05:53:31 +00:00
* @ see Model :: validates ()
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function invalidFields ( $options = array ()) {
2012-05-05 18:04:14 +00:00
return $this -> validator () -> errors ( $options );
2008-05-30 11:40:08 +00:00
}
2011-12-06 20:52:48 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Marks a field as invalid , optionally setting the name of validation
* rule ( in case of multiple validation for field ) that was broken .
2008-05-30 11:40:08 +00:00
*
* @ param string $field The name of the field to invalidate
2009-08-02 19:18:54 +00:00
* @ param mixed $value Name of validation rule that was not failed , or validation message to
2010-03-06 03:07:39 +00:00
* be returned . If no validation key is provided , defaults to true .
2011-07-30 22:38:57 +00:00
* @ return void
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function invalidate ( $field , $value = true ) {
2012-04-28 23:50:22 +00:00
$this -> validator () -> invalidate ( $field , $value );
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns true if given field name is a foreign key in this model .
2008-05-30 11:40:08 +00:00
*
* @ param string $field Returns true if the input string ends in " _id "
2014-07-03 13:36:42 +00:00
* @ return bool True if the field is a foreign key listed in the belongsTo array .
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function isForeignKey ( $field ) {
2008-05-30 11:40:08 +00:00
$foreignKeys = array ();
if ( ! empty ( $this -> belongsTo )) {
2012-09-05 22:22:30 +00:00
foreach ( $this -> belongsTo as $data ) {
2008-05-30 11:40:08 +00:00
$foreignKeys [] = $data [ 'foreignKey' ];
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return in_array ( $field , $foreignKeys );
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2010-03-15 10:55:47 +00:00
* Escapes the field name and prepends the model name . Escaping is done according to the
2010-03-06 03:07:39 +00:00
* current database driver ' s rules .
2008-05-30 11:40:08 +00:00
*
* @ param string $field Field to escape ( e . g : id )
* @ param string $alias Alias for the model ( e . g : Post )
* @ return string The name of the escaped field for this Model ( i . e . id becomes `Post` . `id` ) .
*/
2010-04-05 03:19:38 +00:00
public function escapeField ( $field = null , $alias = null ) {
2008-05-30 11:40:08 +00:00
if ( empty ( $alias )) {
$alias = $this -> alias ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( empty ( $field )) {
$field = $this -> primaryKey ;
}
2013-09-01 19:09:14 +00:00
2010-07-15 03:49:38 +00:00
$db = $this -> getDataSource ();
2010-03-17 15:02:36 +00:00
if ( strpos ( $field , $db -> name ( $alias ) . '.' ) === 0 ) {
2008-05-30 11:40:08 +00:00
return $field ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return $db -> name ( $alias . '.' . $field );
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
* Returns the current record ' s ID
*
2014-07-03 13:36:42 +00:00
* @ param int $list Index on which the composed ID is located
2008-05-30 11:40:08 +00:00
* @ return mixed The ID of the current record , false if no ID
*/
2010-04-05 03:19:38 +00:00
public function getID ( $list = 0 ) {
2008-05-30 11:40:08 +00:00
if ( empty ( $this -> id ) || ( is_array ( $this -> id ) && isset ( $this -> id [ 0 ]) && empty ( $this -> id [ 0 ]))) {
return false ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( ! is_array ( $this -> id )) {
return $this -> id ;
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
if ( isset ( $this -> id [ $list ]) && ! empty ( $this -> id [ $list ])) {
return $this -> id [ $list ];
2012-12-03 15:30:03 +00:00
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( isset ( $this -> id [ $list ])) {
2008-05-30 11:40:08 +00:00
return false ;
}
2011-12-14 06:19:50 +00:00
return current ( $this -> id );
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns the ID of the last record this model inserted .
2008-05-30 11:40:08 +00:00
*
* @ return mixed Last inserted ID
*/
2010-04-05 03:19:38 +00:00
public function getLastInsertID () {
2008-05-30 11:40:08 +00:00
return $this -> getInsertID ();
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns the ID of the last record this model inserted .
2008-05-30 11:40:08 +00:00
*
* @ return mixed Last inserted ID
*/
2010-04-05 03:19:38 +00:00
public function getInsertID () {
2011-08-20 04:43:34 +00:00
return $this -> _insertID ;
2008-05-30 11:40:08 +00:00
}
2009-05-01 21:05:46 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Sets the ID of the last record this model inserted
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ param int | string $id Last inserted ID
2011-07-30 22:38:57 +00:00
* @ return void
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function setInsertID ( $id ) {
2011-08-20 04:43:34 +00:00
$this -> _insertID = $id ;
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns the number of rows returned from the last query .
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ return int Number of rows
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function getNumRows () {
2010-07-15 03:49:38 +00:00
return $this -> getDataSource () -> lastNumRows ();
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Returns the number of rows affected by the last query .
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ return int Number of rows
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function getAffectedRows () {
2010-07-15 03:49:38 +00:00
return $this -> getDataSource () -> lastAffected ();
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Sets the DataSource to which this model is bound .
2008-05-30 11:40:08 +00:00
*
2011-06-20 00:28:40 +00:00
* @ param string $dataSource The name of the DataSource , as defined in app / Config / database . php
2012-04-16 00:33:43 +00:00
* @ return void
2011-07-31 20:55:52 +00:00
* @ throws MissingConnectionException
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function setDataSource ( $dataSource = null ) {
2008-05-30 11:40:08 +00:00
$oldConfig = $this -> useDbConfig ;
2012-09-21 22:30:43 +00:00
if ( $dataSource ) {
2008-05-30 11:40:08 +00:00
$this -> useDbConfig = $dataSource ;
}
2013-09-01 19:09:14 +00:00
2010-07-16 01:46:52 +00:00
$db = ConnectionManager :: getDataSource ( $this -> useDbConfig );
2008-05-30 11:40:08 +00:00
if ( ! empty ( $oldConfig ) && isset ( $db -> config [ 'prefix' ])) {
2010-07-16 02:46:19 +00:00
$oldDb = ConnectionManager :: getDataSource ( $oldConfig );
2008-05-30 11:40:08 +00:00
2014-04-29 12:19:33 +00:00
if ( ! isset ( $this -> tablePrefix ) || ( ! isset ( $oldDb -> config [ 'prefix' ]) || $this -> tablePrefix === $oldDb -> config [ 'prefix' ])) {
2008-05-30 11:40:08 +00:00
$this -> tablePrefix = $db -> config [ 'prefix' ];
}
} elseif ( isset ( $db -> config [ 'prefix' ])) {
$this -> tablePrefix = $db -> config [ 'prefix' ];
}
2014-07-02 21:55:07 +00:00
$schema = $db -> getSchemaName ();
$defaultProperties = get_class_vars ( get_class ( $this ));
if ( isset ( $defaultProperties [ 'schemaName' ])) {
$schema = $defaultProperties [ 'schemaName' ];
}
$this -> schemaName = $schema ;
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
* Gets the DataSource to which this model is bound .
*
2011-08-01 02:57:17 +00:00
* @ return DataSource A DataSource object
2008-05-30 11:40:08 +00:00
*/
2010-07-16 03:47:13 +00:00
public function getDataSource () {
2011-08-20 04:43:34 +00:00
if ( ! $this -> _sourceConfigured && $this -> useTable !== false ) {
$this -> _sourceConfigured = true ;
2010-07-16 01:46:52 +00:00
$this -> setSource ( $this -> useTable );
}
2013-09-01 19:09:14 +00:00
2010-07-15 03:49:38 +00:00
return ConnectionManager :: getDataSource ( $this -> useDbConfig );
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2010-04-04 08:17:43 +00:00
/**
* Get associations
*
* @ return array
*/
2010-04-05 03:19:38 +00:00
public function associations () {
2011-08-20 04:43:34 +00:00
return $this -> _associations ;
2010-04-04 08:17:43 +00:00
}
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Gets all the models with which this model is associated .
2008-05-30 11:40:08 +00:00
*
* @ param string $type Only result associations of this type
2014-11-05 12:03:27 +00:00
* @ return array | null Associations
2008-05-30 11:40:08 +00:00
*/
2010-04-05 03:19:38 +00:00
public function getAssociated ( $type = null ) {
2012-09-14 17:26:30 +00:00
if ( ! $type ) {
2008-05-30 11:40:08 +00:00
$associated = array ();
2011-08-20 04:43:34 +00:00
foreach ( $this -> _associations as $assoc ) {
2008-05-30 11:40:08 +00:00
if ( ! empty ( $this -> { $assoc })) {
$models = array_keys ( $this -> { $assoc });
foreach ( $models as $m ) {
$associated [ $m ] = $assoc ;
}
}
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return $associated ;
2012-12-03 15:30:03 +00:00
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( in_array ( $type , $this -> _associations )) {
2008-05-30 11:40:08 +00:00
if ( empty ( $this -> { $type })) {
return array ();
}
2013-09-01 19:09:14 +00:00
2008-05-30 11:40:08 +00:00
return array_keys ( $this -> { $type });
2012-12-03 15:30:03 +00:00
}
$assoc = array_merge (
$this -> hasOne ,
$this -> hasMany ,
$this -> belongsTo ,
$this -> hasAndBelongsToMany
);
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( array_key_exists ( $type , $assoc )) {
foreach ( $this -> _associations as $a ) {
if ( isset ( $this -> { $a }[ $type ])) {
$assoc [ $type ][ 'association' ] = $a ;
break ;
2008-05-30 11:40:08 +00:00
}
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
return $assoc [ $type ];
2008-05-30 11:40:08 +00:00
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
return null ;
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2012-12-22 22:48:15 +00:00
* Gets the name and fields to be used by a join model . This allows specifying join fields
2009-05-01 21:05:46 +00:00
* in the association definition .
2008-05-30 11:40:08 +00:00
*
2011-07-30 22:38:57 +00:00
* @ param string | array $assoc The model to be joined
2008-05-30 11:40:08 +00:00
* @ param array $keys Any join keys which must be merged with the keys queried
* @ return array
*/
2010-04-05 03:19:38 +00:00
public function joinModel ( $assoc , $keys = array ()) {
2008-05-30 11:40:08 +00:00
if ( is_string ( $assoc )) {
2010-07-14 22:24:19 +00:00
list (, $assoc ) = pluginSplit ( $assoc );
2008-05-30 11:40:08 +00:00
return array ( $assoc , array_keys ( $this -> { $assoc } -> schema ()));
2012-12-03 15:30:03 +00:00
}
2013-09-01 19:09:14 +00:00
2012-12-03 15:30:03 +00:00
if ( is_array ( $assoc )) {
2008-05-30 11:40:08 +00:00
$with = key ( $assoc );
return array ( $with , array_unique ( array_merge ( $assoc [ $with ], $keys )));
}
2013-09-01 19:09:14 +00:00
2009-05-01 21:05:46 +00:00
trigger_error (
2012-09-28 04:57:31 +00:00
__d ( 'cake_dev' , 'Invalid join model settings in %s. The association parameter has the wrong type, expecting a string or array, but was passed type: %s' , $this -> alias , gettype ( $assoc )),
2009-05-01 21:05:46 +00:00
E_USER_WARNING
);
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Called before each find operation . Return false if you want to halt the find
* call , otherwise return the ( modified ) query data .
2008-05-30 11:40:08 +00:00
*
2013-09-10 12:33:11 +00:00
* @ param array $query Data used to execute this query , i . e . conditions , order , etc .
2009-05-01 21:05:46 +00:00
* @ return mixed true if the operation should continue , false if it should abort ; or , modified
2013-09-10 12:33:11 +00:00
* $query to continue with new $query
2012-04-27 02:49:18 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / callback - methods . html #beforefind
2008-05-30 11:40:08 +00:00
*/
2013-09-10 12:33:11 +00:00
public function beforeFind ( $query ) {
2008-05-30 11:40:08 +00:00
return true ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Called after each find operation . Can be used to modify any results returned by find () .
2008-11-08 02:54:07 +00:00
* Return value should be the ( modified ) results .
2008-05-30 11:40:08 +00:00
*
* @ param mixed $results The results of the find operation
2014-07-03 13:36:42 +00:00
* @ param bool $primary Whether this model is being queried directly ( vs . being queried as an association )
2008-05-30 11:40:08 +00:00
* @ return mixed Result of the find operation
2012-04-27 02:49:18 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / callback - methods . html #afterfind
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function afterFind ( $results , $primary = false ) {
2008-05-30 11:40:08 +00:00
return $results ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Called before each save operation , after validation . Return a non - true result
* to halt the save .
2008-05-30 11:40:08 +00:00
*
2013-09-10 00:20:22 +00:00
* @ param array $options Options passed from Model :: save () .
2014-07-03 13:36:42 +00:00
* @ return bool True if the operation should continue , false if it should abort
2012-04-27 02:49:18 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / callback - methods . html #beforesave
2013-09-10 00:20:22 +00:00
* @ see Model :: save ()
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function beforeSave ( $options = array ()) {
2008-05-30 11:40:08 +00:00
return true ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-11-08 02:54:07 +00:00
* Called after each successful save operation .
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ param bool $created True if this save created a new record
2013-09-10 00:20:22 +00:00
* @ param array $options Options passed from Model :: save () .
2011-07-30 22:38:57 +00:00
* @ return void
2012-04-27 02:49:18 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / callback - methods . html #aftersave
2013-09-10 00:20:22 +00:00
* @ see Model :: save ()
2008-05-30 11:40:08 +00:00
*/
2013-09-10 00:20:22 +00:00
public function afterSave ( $created , $options = array ()) {
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2009-05-22 01:20:47 +00:00
* Called before every deletion operation .
2008-05-30 11:40:08 +00:00
*
2014-07-03 13:36:42 +00:00
* @ param bool $cascade If true records that depend on this record will also be deleted
* @ return bool True if the operation should continue , false if it should abort
2012-04-27 02:49:18 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / callback - methods . html #beforedelete
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function beforeDelete ( $cascade = true ) {
2008-05-30 11:40:08 +00:00
return true ;
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Called after every deletion operation .
2008-05-30 11:40:08 +00:00
*
2011-07-30 22:38:57 +00:00
* @ return void
2012-04-27 02:49:18 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / callback - methods . html #afterdelete
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function afterDelete () {
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2009-11-04 17:36:17 +00:00
* Called during validation operations , before validation . Please note that custom
2008-10-31 19:05:30 +00:00
* validation rules can be defined in $validate .
2008-05-30 11:40:08 +00:00
*
2013-09-05 13:38:29 +00:00
* @ param array $options Options passed from Model :: save () .
2014-07-03 13:36:42 +00:00
* @ return bool True if validate operation should continue , false to abort
2012-04-27 02:49:18 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / callback - methods . html #beforevalidate
2013-09-05 13:38:29 +00:00
* @ see Model :: save ()
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function beforeValidate ( $options = array ()) {
2008-05-30 11:40:08 +00:00
return true ;
}
2009-07-24 19:18:37 +00:00
2012-05-07 04:08:29 +00:00
/**
* Called after data has been checked for errors
*
* @ return void
*/
public function afterValidate () {
}
2008-05-30 11:40:08 +00:00
/**
2008-10-31 19:05:30 +00:00
* Called when a DataSource - level error occurs .
2008-05-30 11:40:08 +00:00
*
2011-07-30 22:38:57 +00:00
* @ return void
2012-04-27 02:49:18 +00:00
* @ link http :// book . cakephp . org / 2.0 / en / models / callback - methods . html #onerror
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
public function onError () {
2008-05-30 11:40:08 +00:00
}
2009-07-24 19:18:37 +00:00
2008-05-30 11:40:08 +00:00
/**
2011-08-20 04:43:34 +00:00
* Clears cache for this model .
2008-05-30 11:40:08 +00:00
*
* @ param string $type If null this deletes cached views if Cache . check is true
2010-03-06 03:07:39 +00:00
* Will be used to allow deleting query cache also
2013-10-24 00:59:58 +00:00
* @ return mixed True on delete , null otherwise
2008-05-30 11:40:08 +00:00
*/
2011-05-28 20:38:46 +00:00
protected function _clearCache ( $type = null ) {
2013-09-28 08:16:23 +00:00
if ( $type !== null || Configure :: read ( 'Cache.check' ) !== true ) {
return ;
}
2013-10-24 00:59:58 +00:00
$pluralized = Inflector :: pluralize ( $this -> alias );
$assoc = array (
strtolower ( $pluralized ),
Inflector :: underscore ( $pluralized )
);
2013-09-28 08:16:23 +00:00
foreach ( $this -> _associations as $association ) {
2013-10-24 00:59:58 +00:00
foreach ( $this -> { $association } as $className ) {
$pluralizedAssociation = Inflector :: pluralize ( $className [ 'className' ]);
if ( ! in_array ( strtolower ( $pluralizedAssociation ), $assoc )) {
$assoc = array_merge ( $assoc , array (
strtolower ( $pluralizedAssociation ),
Inflector :: underscore ( $pluralizedAssociation )
));
2008-05-30 11:40:08 +00:00
}
}
}
2013-10-24 00:59:58 +00:00
clearCache ( array_unique ( $assoc ));
2013-09-28 08:16:23 +00:00
return true ;
2008-05-30 11:40:08 +00:00
}
2012-03-04 19:18:04 +00:00
2012-03-22 11:18:57 +00:00
/**
2012-11-27 07:15:23 +00:00
* Returns an instance of a model validator for this class
2012-03-22 11:18:57 +00:00
*
2014-06-04 18:58:55 +00:00
* @ param ModelValidator $instance Model validator instance .
2012-11-28 22:30:47 +00:00
* If null a new ModelValidator instance will be made using current model object
2012-04-28 23:50:22 +00:00
* @ return ModelValidator
2012-03-22 11:18:57 +00:00
*/
2012-11-27 07:15:23 +00:00
public function validator ( ModelValidator $instance = null ) {
if ( $instance ) {
$this -> _validator = $instance ;
} elseif ( ! $this -> _validator ) {
2012-04-28 23:50:22 +00:00
$this -> _validator = new ModelValidator ( $this );
2012-03-22 11:18:57 +00:00
}
2013-09-01 19:09:14 +00:00
2012-03-22 11:18:57 +00:00
return $this -> _validator ;
}
2008-05-30 11:40:08 +00:00
}