Return Object Instead Of Array

I am very very new to Yii, so it’s possible my one issue is not my only issue.

I am trying to use the tablesorter extension and running into some issues when using queryAll();

Everything is perfect if I use:




$records=User::model()->findAll();

$this->render('admin',array(

     'records'=>$records,

));



But then when switching to a custom sql statement I get an error of "get_class() expects parameter 1 to be object, array given"




$sql = "SELECT * FROM user LEFT JOIN parties on parties.id = user.id";

$usercollect=Yii::app()->db->createCommand($sql)->queryAll();

	$this->render('index', array(

	'records'=>$usercollect,

));



After a bit of research, it appears using the queryAll() returns an array, while using the model it returns an array. I would like to continue using the createCommand and custom query in this fashion as I am still trying to learn Yii but also have some pretty advanced SQL statements to add once I get the testing done and haven’t gotten the relationships / query builder down yet.

Any help is greatly appreciated.

Working with sql statements is ok, if your views doesn’t contain components that needs an array of models as data.

I prefer direct sql-statements too if they are complex or for better performance on viewing recordlists where I don’t need methods from a model.

The problem is the code in your ‘records’ view.

What widgets/component do you use in your view ‘records’?

Do they support array records?

Do you render like




foreach($records as $record) {


   echo $record['username'];


   //for more complex record details use a own view with renderPartial

   //$this->renderPartial('_record',array('record'=>$record));  


}




Using models/activerecords saves a lot of time to implement CRUD operations by using gii.

For admin operations performance is not so important.

Thanks for the fast response!

You are correct with the view being the problem, as like you said it doesn’t support array.

I actually stumbled across "$usercollect->setFetchMode(PDO::FETCH_OBJ);" which appears to have solved my issues.

You can generate your model or a standard object in the records loop too:





foreach($records as $record) {


   $record = (object)$record; //typecast to standard object


   //or create the model if necessary, but think about the overhead/loss of performance

   $model = new User();

   $model->setAttributes($record,false); //don't validate the model attributes


   echo $record['username'];


   //for more complex record details use a own view with renderPartial

   //$this->renderPartial('_record',array('record'=>$record));  


}