Create Activerecord Object From Array

Im new to Yii and ActiveRecord and have been playing around with the Yii::app()->db->createCommand() method. Also, I’m studying for the MySQL certifications exam so I want to practice creating queries.

The queries return arrays for tables and I was wondering what is the proper way to create an AR object from this data? I see that CActiveRecord has a method called populateRecord(). However, some of my custom methods don’t work because all the attributes aren’t set (I’m assuming the ones that don’t have rules). If I use setAttributes() my methods work. Just wondering if this method is ok to use? Also, is there any more of a performance hit constructing AR objects myself versus Yii constructing them? Heres what I’m doing for now:




$cmd = Yii::app()->db->createCommand($q);


$result = $cmd->query();


echo 'Total Objects: ' , count($result);

$filesArray = array();

foreach($result as $row):

	$file = new File;

	$file->setAttributes($row, FALSE);

	$filesArray[] = $file;

endforeach;

die(pr($filesArray));



setAttributes() is the correct method to use. It’s used as a property when populating a model from a form.

Assuming that you’re populating objects of a single active record class each time (and that you really want to write the SQL yourself), this might work better for you:




$files = File::model()->findAllBySql($q);



That will automatically populate the model fields.

Hey thanks for the tip. That approach is a lot more elegant and works perfectly.