[solved] any way to check if a column exists in an AR object?

As in the book, I want to extend CActiveRecord so that when an object has columns such as "creation_stamp", "modification_stamp", "create_user_id" etc they are automatically updated.

But I want this class to be usable even for objects that don’t include all of those columns, so that an object can only have cdate/mdate or cuser/muser or neither.

Something like

	protected function beforeValidate() {

		if ($this->isNewRecord) {

		//NEW record


			if (property_exists($this, 'cstamp'))

				$this->cstamp = NOW;


			if (property_exists($this, 'mstamp'))

				$this->mstamp = NOW;

		} else {

		//OLD record


			if (property_exists($this, 'mstamp'))

				$this->mstamp = NOW;


		return parent::beforeValidate();


Using property_exists() does not work of course since columns are "magically" accessible properties, and isset() is not enough since it will return false even when a property exists but is null.

Is there a way to check if a column property exists?

Would array_key_exists(‘col’, $obj->attributes) be sufficient?

Of course, you can read all (reverse engineered) database tables, columns and their properties.

try out:

$model = MyModel::model();

$table = Yii::app()->getDb()->getSchema()->getTable($model->tableName());

$columnNames = $table->getColumnNames();

$table has table properties, $columnNames holds all column names.


You should be able to do what you want with the hasAttribute() method of the CActiveRecord.

See: http://www.yiiframework.com/doc/api/1.1/CActiveRecord#hasAttribute-detail