Permalink
Browse files

Optimizing various finds when deleting records and updating counter c…

…ache to avoid extra queries, unnecessary joins and callbacks triggering
  • Loading branch information...
1 parent 182b13f commit 2b342d96d66d2ad1568ebac0ab8b76984bee96e5 @ADmad ADmad committed Aug 3, 2011
Showing with 17 additions and 6 deletions.
  1. +17 −6 lib/Cake/Model/Model.php
View
23 lib/Cake/Model/Model.php
@@ -1546,8 +1546,8 @@ public function updateCounterCache($keys = array(), $created = false) {
if (!array_key_exists($foreignKey, $keys)) {
$keys[$foreignKey] = $this->field($foreignKey);
}
- $recursive = (isset($assoc['counterScope']) ? 1 : -1);
- $conditions = ($recursive == 1) ? (array)$assoc['counterScope'] : array();
+ $recursive = (isset($assoc['counterScope']) ? 0 : -1);
+ $conditions = ($recursive === 0) ? (array)$assoc['counterScope'] : array();
if (isset($keys['old'][$foreignKey])) {
if ($keys['old'][$foreignKey] != $keys[$foreignKey]) {
@@ -1562,7 +1562,7 @@ public function updateCounterCache($keys = array(), $created = false) {
}
$conditions[$fkQuoted] = $keys[$foreignKey];
- if ($recursive == 1) {
+ if ($recursive === 0) {
$conditions = array_merge($conditions, (array)$assoc['counterScope']);
}
$count = intval($this->find('count', compact('conditions', 'recursive')));
@@ -1960,15 +1960,25 @@ public function delete($id = null, $cascade = true) {
$this->_deleteLinks($id);
$this->id = $id;
+ $updateCounterCache = false;
if (!empty($this->belongsTo)) {
+ foreach ($this->belongsTo as $parent => $assoc) {
+ if (!empty($assoc['counterCache'])) {
+ $updateCounterCache = true;
+ break;
+ }
+ }
+
$keys = $this->find('first', array(
'fields' => $this->__collectForeignKeys(),
- 'conditions' => array($this->alias . '.' . $this->primaryKey => $id)
+ 'conditions' => array($this->alias . '.' . $this->primaryKey => $id),
+ 'recursive' => -1,
+ 'callbacks' => false
));
}
if ($db->delete($this, array($this->alias . '.' . $this->primaryKey => $id))) {
- if (!empty($this->belongsTo)) {
+ if ($updateCounterCache) {
$this->updateCounterCache($keys[$this->alias]);
}
$this->Behaviors->trigger('afterDelete', array(&$this));
@@ -2035,7 +2045,8 @@ protected function _deleteLinks($id) {
$records = $this->{$joinModel}->find('all', array(
'conditions' => array_merge(array($this->{$joinModel}->escapeField($data['foreignKey']) => $id)),
'fields' => $this->{$joinModel}->primaryKey,
- 'recursive' => -1
+ 'recursive' => -1,
+ 'callbacks' => false
));
if (!empty($records)) {
foreach ($records as $record) {

0 comments on commit 2b342d9

Please sign in to comment.