using ActiveRecord::update()-method


what is correct usage of this method?

I tried this:

$user = User::model()->findByPk(1);

$user->update(array('lastLogin' => date('Y-m-d H:i:s')));

throwing CDbException: No columns are being updated for table "user".


ok this works,

$user = User::model()->findByPk(1);

$user->lastLogin = date('Y-m-d H:i:s');


Better approach

$user = User::model()->findByPk(1);

$user->lastLogin = new CDbExpression("NOW()");



That depends - it’s not necessarily better. You have to think careful about timezone settings in PHP and MySQL.


Even shorter:

User::model()->updateByPk(1,array('lastLogin'=>date('Y-m-d H:i:s')));

It is better considering concurrency problem.

Using PHP date is not safe this case.


thanx yiiframework, just forgot time - now I have a black pizza :lol:

I don’t really understand. Can you maybe give an example for a problematic situation? I’m willing to learn. :)

BTW: We’ve already discussed some “best practices” for date/time handling with PHP + DB here.

Trying an example:

Process A -> Incoming at 08:30:00.00 (PHP date - the same)

Process B -> Incoming at 08:30:00.05 (PHP date - the same)

Process A -> Process Time: 50ms

Process B -> Process Time: 30ms

Process A -> DB request at 08:30:00.50

Process B -> DB request at 08:30:00.35

Process A -> date: 08:30:00.00 (received by DB at 08:30:00.50)

Process B -> date: 08:30:00.05 (received by DB at 08:30:00.35)

Analysing by DB date, process A was saved before process B, which is not true. For concurrency issues, it is safer to use DB dates (got at "insert" moment)

Good point, thanks. Even if i can’t think of many applications where this really matters it’s good to keep that in mind.