createCommand queryAll returning array instead of objects

Hi everybody!

I’m using the new query builder launched with Yii 1.1.6 version, and when trying to get a property of the objects returned by the query, I get the following error…




Trying to get property of non-object...

... $user->user_id



and the query I’m using is…





$rval = Yii::app()->db->createCommand()

                        ->select('u.*')

                        ->from('user u')

                        ->where('u.role_id = :role_id', array(':role_id' => '1'))

                        ->queryAll();



If I make a var_dump of the results this is what I get…




array(1) { [0]=> array(13) { ["user_id"]=> string(1) "1" ["role_id"]=> string(1) "1" ["company_id"]=> string(1) "1" ["user_name"]=> string(5) "admin" ["password"]=> string(5) "admin" ["email"]=> string(19) "xxx@gmail.com" ["first_name"]=> string(7) "Ricardo" ["last_name"]=> string(12) "Ricardo" ["img"]=> NULL ["date_format"]=> string(5) "d-m-Y" ["send_notifications"]=> string(1) "1" ["language"]=> string(2) "es" ["created_at"]=> NULL } }



It seems to me that its not an ActiveRecord object… isn’t it?

If I do the same query using the model()->findByAttributes and I var_dump the result, this one is very different from the first one…





User::model()->findByAttributes(array('role_id'=>  '1'));




the result is




object(User)#97 (12) { ["_md":"CActiveRecord":private]=> object(CActiveRecordMetaData)#70 (5) { ["tableSchema"]=> object(CMysqlTableSchema)#72 (9) { ["schemaName"]=> NULL ["name"]=> string(4) "user" ["rawName"]=> string(6) "`user`" ["primaryKey"]=> string(7) "user_id" ["sequenceName"]=> string(0) "" ["foreignKeys"]=> array(2) { ["company_id"]=> array(2) { [0]=> string(7) "company" [1]=> string(10) "company_id" } ["role_id"]=> array(2) { [0]=> string(4) "role" [1]=> string(7) "role_id" } } ["columns"]=> array(13) { ..........



Why is createCommand of the query builder not returning ActiveRecords??? Am I doing something wrong?

Thanks in advance!

According to the docs it’s the expected behavior.

Thanks for your response!

Is there a way to make it return AvtiveRecord objects? Or should I use the User::model()->findByAttributes method instead?

I think that active record and query builder follow different paths.

The query builder has been introducted, I guess, for avoid the overhead of AR in situation in wich you cannot limit the number of records.

Check this post by Mike where he described best usage for DAO, Query Builder and Active Record - http://www.yiiframework.com/forum/index.php?/topic/15253-cdbcriteria-vs-findbysql/page__view__findpost__p__76259

Ok! now I understand the differences between them!!!

Thanks!

You can take a look at CActiveRecord.populateRecords() method.