diff --git a/lib/Model.php b/lib/Model.php index 76a1e399a..f9456534b 100644 --- a/lib/Model.php +++ b/lib/Model.php @@ -1270,6 +1270,33 @@ public function set_timestamps() $this->created_at = $now; } + /** + * Touch a model, updates `updated_at` and any other column given as argument. + * + * Please note that no validation is performed and only the after_touch, after_commit and after_rollback callbacks are executed. + * + * @param string|array $keys... + * @return bool True if update succeeds + * @throws ActiveRecord\ActiveRecordException if object is a new record + */ + public function touch($keys = array() /*[, $key...] */) + { + if($this->is_new_record()) + throw new ActiveRecordException('Cannot touch on a new record object'); + + if(!is_array($keys)) + $keys = func_get_args(); + + if(!in_array('updated_at', $keys)) + $keys[] = 'updated_at'; + + $now = date('Y-m-d H:i:s'); + $attributes = array_fill_keys($keys, $now); + + $this->set_attributes($attributes); + return $this->update(false); + } + /** * Mass update the model with attribute data and saves to the database. * diff --git a/test/ActiveRecordWriteTest.php b/test/ActiveRecordWriteTest.php index c0351413d..c84d6dbe1 100644 --- a/test/ActiveRecordWriteTest.php +++ b/test/ActiveRecordWriteTest.php @@ -441,4 +441,46 @@ public function test_update_our_datetime() $this->assert_true($our_datetime === $author->some_date); } + public function test_touch() + { + $author = Author::create(array('name' => 'MC Hammer')); + $updated_at = $author->updated_at = new DateTime('yesterday'); + $author->save(); + $author->touch(); + $this->assertGreaterThan($updated_at, $author->updated_at); + } + + /** + * @expectedException ActiveRecord\ActiveRecordException + * @expectedExceptionMessage Cannot touch on a new record object + */ + public function test_touch_on_new_record() + { + $author = new Author(array('name' => 'MC Hammer')); + $author->touch(); + } + + public function test_touch_with_additional_keys() + { + $author = Author::create(array('name' => 'MC Hammer')); + $updated_at = $author->updated_at = new DateTime('yesterday'); + $some_date = $author->some_date = new DateTime('yesterday'); + $author->save(); + $author->touch(array('some_date')); + $this->assertGreaterThan($updated_at, $author->updated_at); + $this->assertGreaterThan($some_date, $author->some_date); + } + + public function test_touch_with_scalar() + { + $author = Author::create(array('name' => 'MC Hammer')); + $updated_at = $author->updated_at = new DateTime('yesterday'); + $some_date = $author->some_date = new DateTime('yesterday'); + $author->save(); + $author->touch('some_date'); + $this->assertGreaterThan($updated_at, $author->updated_at); + $this->assertGreaterThan($some_date, $author->some_date); + } + + }