Skip to content

Commit

Permalink
Add basic implementation of deleteAll().
Browse files Browse the repository at this point in the history
  • Loading branch information
markstory committed Jun 23, 2013
1 parent 21d0236 commit b59c037
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 0 deletions.
23 changes: 23 additions & 0 deletions lib/Cake/ORM/Table.php
Expand Up @@ -506,4 +506,27 @@ public function updateAll($fields, $conditions) {
return true;
}

/**
* Delete all matching rows.
*
* Deletes all rows matching the provided conditions.
*
* This method will *not* trigger beforeDelete/afterDelete events. If you
* need those first load a collection of records and delete them.
*
* This method will *not* execute on associations `cascade` attribute. You should
* use database foreign keys + ON CASCADE rules if you need cascading deletes combined
* with this method.
*
* @param array $conditions An array of conditions, similar to those used with find()
* @return boolean Success
*/
public function deleteAll($conditions) {
$query = $this->_buildQuery();
$query->delete($this->table())
->where($conditions);
$query->execute();
return true;
}

}
36 changes: 36 additions & 0 deletions lib/Cake/Test/TestCase/ORM/TableTest.php
Expand Up @@ -412,4 +412,40 @@ public function testUpdateAllFailure() {
$table->updateAll(['username' => 'mark'], []);
}

/**
* Test deleting many records.
*
* @return void
*/
public function testDeleteAll() {
$table = new Table(['table' => 'users', 'connection' => $this->connection]);
$result = $table->deleteAll(['id <' => 4]);
$this->assertTrue($result);

$result = $table->find('all')->toArray();
$this->assertCount(1, $result, 'Only one record should remain');
$this->assertEquals(4, $result[0]['id']);
}

/**
* Test that exceptions from the Query bubble up.
*
* @expectedException Cake\Database\Exception
*/
public function testDeleteAllFailure() {
$table = $this->getMock(
'Cake\ORM\Table',
['_buildQuery'],
['table' => 'users', 'connection' => $this->connection]
);
$query = $this->getMock('Cake\ORM\Query', ['execute'], [$this->connection]);
$table->expects($this->once())
->method('_buildQuery')
->will($this->returnValue($query));
$query->expects($this->once())
->method('execute')
->will($this->throwException(new \Cake\Database\Exception('Not good')));
$table->deleteAll(['id >' => 4]);
}

}

0 comments on commit b59c037

Please sign in to comment.