auto `created` and `updated` columns

I'm trying to get my created and updated columns to automatically update/set when saving data.

<?php


public function beforeSave() {


	if ($this->isNewRecord)


		$this->created = 'Now()';


	else


		$this->modified = 'Now()';


	return true;


}


But that doesn't work because Yii escapes Now() so it's not treated as a function.  How should I go about this then?  Can I use mysql functions in AR at all?

I've tried solving this on the database side but I found no satisfactory solution.

Thanks!

Jonah

I found a solution:

if ($this->isNewRecord)

$this-&gt;created = gmdate(&quot;Y-m-d H:i:s&quot;, time());

else

$this-&gt;modified = gmdate(&quot;Y-m-d H:i:s&quot;, time());

But I'm still curious; is it possible/how to use mysql functions? thanks

I can't think of a way to do it using AR because it would require the columns not to be escaped. Perhaps you can define the column to the default value as NOW() when creating the table? And then setting the column to be null so that it can be set with the NOW value? I am not sure if this works or not.

I may try that.  BTW I believe CakePHP had the same problem.  They had one work-around but it was ugly.

Maybe you find this thread interesting, too: http://www.yiiframew…3.msg1336.html. Combined with your idea, my beforeSave() method will look like this:



public function beforeSave() {


    if ($this->isNewRecord)


        $this->createdate = gmdate('Y-m-d H:i:s');





    // TIMESTAMP column will get auto-updated by MySQL


    $this->changedate=null;





    return true;


}


A trick that Doctrine uses I believe is using a Db_Statement object of some kind. So instead of



$this->modified->='now()'; //will be escaped by the db abstraction layer and gives all sorts of problems


To do this



$this->modified=new Db_Statement('now()');


The database abstraction layer will recognize the object and not escape it. Perhaps just use the __toString() method.

That sounds a good solution. Could you please crate a ticket for this (Db_Statement)? Thanks!

@dalip

I like it.  I'll wait just for the enhancement patch then.