Model->Behaviors->load('Tools.Reset', array(...)); * $this->Model->resetRecords(); * * For tables with lots of records you might want to use a shell and the CLI to invoke the reset/update process. * * @author Mark Scherer * @license MIT * @cakephp 2.x * @version 1.0 */ class ResetBehavior extends ModelBehavior { protected $_defaults = array( 'limit' => 100, // batch of records per loop 'timeout' => null, // in seconds 'fields' => array(), // if not displayField 'validate' => true, // trigger beforeValidate callback 'updateTimestamp' => false, // update modified/updated timestamp 'scope' => array(), // optional conditions 'callback' => null, ); /** * Configure the behavior through the Model::actsAs property * * @param object $Model * @param array $config */ public function setup(Model $Model, $config = null) { if (is_array($config)) { $this->settings[$Model->alias] = array_merge($this->_defaults, $config); } else { $this->settings[$Model->alias] = $this->_defaults; } } /** * Regenerate all records (including possible beforeValidate/beforeSave callbacks). * * @param Model $Model * @param array $conditions * @param integer $recursive * @return boolean Success */ public function resetRecords(Model $Model, $params = array()) { $recursive = -1; extract($this->settings[$Model->alias]); $defaults = array( 'page' => 1, 'limit' => $limit, 'fields' => array(), 'order' => $Model->alias.'.'.$Model->displayField . ' ASC', 'conditions' => $scope, 'recursive' => $recursive, ); if (!empty($fields)) { if (!$Model->hasField($fields)) { throw new CakeException('Model does not have fields ' . print_r($fields, true)); } $defaults['fields'] = array_merge(array($Model->primaryKey), $fields); } else { $defaults['fields'] = array($Model->primaryKey); if ($Model->displayField !== $Model->primaryKey) { $defaults['fields'][] = $Model->displayField; } } if (!$updateTimestamp) { $fields = array('modified', 'updated'); foreach ($fields as $field) { if ($Model->schema($field)) { $defaults['fields'][] = $field; break; } } } $params = array_merge($defaults, $params); $count = $Model->find('count', compact('conditions')); $max = ini_get('max_execution_time'); if ($max) { set_time_limit (max($max, $count / $limit)); } while ($rows = $Model->find('all', $params)) { foreach ($rows as $row) { $Model->create(); $fields = $params['fields']; if ($callback) { $Model->{$callback}($row, $fields); } $res = $Model->save($row, $validate, $fields); if (!$res) { throw new CakeException(print_r($Model->validationErrors, true)); } } $params['page']++; if ($timeout) { sleep((int)$timeout); } } return true; } }