The irony of Model::deleteAll()

Published on and tagged with cakephp  model

Today I wanted to implement some functionality to delete all records of a table. Easy, there is a deleteAll() method in the Model class I can use for this purpose. So I wrote the following statement:

$this->MyModel->deleteAll(array(), false);

As I executed that code, nothing happened. No delete statement was generated. Hm. So I looked at the source of the deleteAll() method, and what’s there? The method simply returns false if you provide an empty $conditions parameter:

if (empty($conditions)) {
    return false;
}

And as this is not a bug (see ticket 3699), this means you have to provide a dummy condition if you want to delete all entries of a table:

$this->MyModel->deleteAll(array('1 = 1'), false);

or

$this->MyModel->deleteAll('1 = 1', false);

It’s a bit ironic that you have to use a workaround when using deleteAll() to delete all entries of a table, isn’t it? ;-)

54 comments baked

  • Cameron Junge

    Ok, coming in a little late…

    how about a constant?

    define(‘DELETE_ALL_RECORDS’, true);
    // ideally a class constant, maybe Model::$DELETE_ALL_RECORDS?

    Just for use as a flag really. I like the idea of using “true” rather than just assuming blank conditions mean you want to do it (could be a bug for instance). A little conscious thought isn’t always a bad thing, and TRUE is a lot more intuitive than “1 = 1”.

  • cakebaker

    @Cameron: At least to me it is redundant if you have to write something like:

    $this->MyModel->deleteAll(DELETE_ALL_RECORDS);
    

    But as you see in the other comments, half of the people think it is good to have such a flag, and the other half think it is not necessary ;-)

  • Fordnox

    Have not read all the comment and i do not know what is being discussed in there, but for me is is easier to write such function in app_model.php

    function truncate() {
    return $this->query(“TRUNCATE “.$this->table);
    }

  • cakebaker

    @Fordnox: Yes, that’s a good alternative (at least if it is ok that auto_increment fields get reset).

Bake a comment




(for code please use <code>...</code> [no escaping necessary])

© daniel hofstetter. Licensed under a Creative Commons License