Cruzer
Cruzer

Reputation: 31

CakePHP delete records older than 5 days

Basically, I want to do this in CakePHP:

delete from myTable as mytable where datediff(now(), mytable.date) > 5

And I don't know how to do it with the $this->Model->delete() function?

Upvotes: 1

Views: 1948

Answers (3)

bastey
bastey

Reputation: 679

In CakePHP 3.x you should use this:

// In a controller or table method.
$time = \Cake\I18n\Time::now();
$time->modify('-5 days');
$query = $this->Model->deleteAll(['Model.date <=' => $time->format('Y-m-d H:i:s')]);

Upvotes: 1

Tim Sanders
Tim Sanders

Reputation: 851

The easiest way to preform a custom query is use Model::query method. It's not the recommend way, but it seems like you want a quick/dirty answer.

$this->MyModel->query("delete from myTable as mytable where datediff(now(), 
                        mytable.date) > 5");

If you do this method make sure you escape the query string to prevent SQLi attacks.

Recommended way:

Use Model::deleteAll(mixed $conditions, $cascade = true, $callbacks = false)

$conditions = array('datediff(now(), Model.date) > 5');
$this->MyModel->deleteAll($conditions,false);

Upvotes: 1

Holt
Holt

Reputation: 37606

You need to use deleteAll:

$this->Model->deleteAll(array(
    'datediff(now(), Model.date) > 5'
)) ;

Upvotes: 3

Related Questions