3

I have a timestamp behavior (yii2) that looks like this (taken from user guide example)...

public function behaviors()
{
    return [
            'timestamp' => [
                    'class' => TimestampBehavior::className(),
                    'value' => new Expression('NOW()'),
            ],
         ];
}

But is it not better to use a PHP DateTime expression like...

'value' => (new /DateTime('NOW'))->format('Y-m-d H:i:s')

Seems to me like it would be better to work with one clock rather than possibly two (in case the database server is separate and time not in sync, which is not unlikely.) Especially if I'm using DateTime in my code to check other conditions.

Which approach is better and why?

1
  • 1
    One drawback with using DB Expressin in yii2 is that the model attribute is not updated after $model->save(). It still contains "new Expression('NOW()')". To get the actual value the model need to be loaded from database with "$model->refresh()". By using PHP datetime the final value is present right away. (Found that out when making a Rest API with the default Rest classes. After creating something the value echoed back still was an Expression and not a value.) Commented Nov 8, 2015 at 17:19

1 Answer 1

1

Expression class created a DBMS function inside the SQL query, it works no matter which date type (or format, it is possible to force the date format in some DBMS) you have in your column. If you change the value of a behavior you should take care the format and type of your column does match, otherwise some time you would get an error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.