saving new Model, setIsNewRecord and __construct

I faced a bug today which I didn’t find help for in forums for, so I thought I’d share in case others face the same problem.

The problem (generic):


$model = new myModel();

$model->attr = "value";

if($model->validate())

  echo "validate ok";

if($model->save())

  echo "save ok";

Was printing


"validate ok"

"save ok"

But wasn’t saving.

Logging showed that instead of the expected insert query it was running an update query:


UPDATE `mymodel` SET (...) WHERE `mymodel`.`id` IS NULL

This turned out to work:


$model = new myModel();

$model->attr = "value";


$model->setIsNewRecord(true);


if($model->validate())

  echo "validate ok";

if($model->save())

  echo "save ok";

I noticed that setIsNewRecord sets the private property _new in CActiveRecord.

Why wasn’t it setting it for $model = new myModel(); ?

Finally, I discovered the source of the problem which was:


class myModel extends CActiveRecord

{

	public function __construct()

	{

		doSomething();

	}

}

It should actually have been:


class myModel extends CActiveRecord

{

	public function __construct()

	{

		doSomething();

		return parent::__construct();

	}

}

Have u tried to see what will $model->isNewRecord return, it should return true for any new record.

His problem is solved now; he just needed to call the parent constructor.