Reputation: 34673
I have a MySQL column that is of timestamp
type, called updated
. I want Yii to fetch it by default with SELECT UNIX_TIMESTAMP(status_updated)
in the Active Record model. So that I can do this:
$timestamp_as_integer = MyModel::model()->findByPk(1)->updated;
Is this easily possible? Right now I'm parsing the YYYY-MM-DD hh:mm:ss
format that MySQL returns for all date time column types to get the integer timestamp but I was curios if I can force the database to do it for me?
Upvotes: 0
Views: 451
Reputation: 2122
Off the top of my head, but this should work.
$timestamp_as_integer = MyModel::model()->findByPk(1, array(
'select' => array(new CDbExpression('UNIX_TIMESTAMP(updated) as updated'))
))->updated;
Upvotes: 0
Reputation: 8597
Another approach is to write a getter:
public function getUpdatedTimestamp()
{
return strtotime($this->updated);
}
The nice thing is, you can now access it as $model->updatedTimestamp
and still have the original DB value in $model->updated
.
Upvotes: 1
Reputation: 79032
Perform the conversion in the model:
protected function afterFind() {
parent::afterFind();
$this->status_updated = strtotime($this->status_updated);
}
Now after you perform a 'find' on the model, the property status_updated
will automatically have it in int
timestamp format.
Upvotes: 1