Skip to content

Commit

Permalink
Don't use a subquery for deletes.
Browse files Browse the repository at this point in the history
MySQL doesn't like deleting from a table that it is also selecting
records from. Use lower level query APIs to get the desired results.
  • Loading branch information
markstory committed Oct 11, 2017
1 parent e60ae26 commit 0c95586
Showing 1 changed file with 5 additions and 6 deletions.
11 changes: 5 additions & 6 deletions src/ORM/Behavior/TreeBehavior.php
Expand Up @@ -222,19 +222,18 @@ public function beforeDelete(Event $event, EntityInterface $entity)
$left = $entity->get($config['left']);
$right = $entity->get($config['right']);
$diff = $right - $left + 1;
$primaryKey = $this->_getPrimaryKey();

if ($diff > 2) {
/* @var \Cake\Database\Expression\QueryExpression $expression */
$finder = $this->_scope($this->_table->find())
->select([$primaryKey], true)
$query = $this->_scope($this->_table->query())
->delete()
->where(function ($exp) use ($config, $left, $right) {
/* @var \Cake\Database\Expression\QueryExpression $exp */
return $exp
->gte($config['leftField'], $left + 1)
->lte($config['leftField'], $right - 1);
});

$this->_table->deleteAll([$primaryKey . ' IN' => $finder]);
$statement = $query->execute();
$statement->closeCursor();
}

$this->_sync($diff, '-', "> {$right}");
Expand Down

0 comments on commit 0c95586

Please sign in to comment.