Using active records with CDbCommand

I’m fairly new to yii and I have a feeling I’m using an incorrect approach to loading active records with query results.





     $queue = new UserQueue();


    $db = Yii::app()->db;

    

    $queueCommand = $db->createCommand()

       ->select('q.*')

       ->from('user_queue q')

       ->group('q.id')

       ->order('(select count(id) from asset where asset.owner_id=q.user_id and available=0)-(select count(id) from trade where trade.user_id=q.user_id) desc,(select count(id) from asset where asset.owner_id=q.user_id) desc')

       ->where('q.priority=:priority');


   for($priority = 1; $priority <= 10; $priority++ ) {

            

      foreach($queueCommand->query(array(':priority'=>$priority)) as $queueData) {

        

        $queue->attributes = $queueData;



What I am trying to do is load query rows in the active record so that I can use methods in the model class, and update the object as necessary. What I am finding is that $queue does not have the id set and it treats it as a new record, so I cannot call save() on it.

I am using a complex order clause with subqueries and not sure they can be expressed with CDbCriteria.

Welcome to the forum!!

Yes, you are mistaking the approach. You are using the new query builder wich is used for retrive data in array, not active records.

For active records query you can use CDbCriteria like that:




 $queueCommand = $db->createCommand()

       ->select('q.*')

       ->from('user_queue q')

       ->group('q.id')

       ->order('(select count(id) from asset where asset.owner_id=q.user_id and available=0)-(select count(id) from trade where trade.user_id=q.user_id) desc,(select count(id) from asset where asset.owner_id=q.user_id) desc')

       ->where('q.priority=:priority');


$criteria = new CDBCriteria;

$criteria->select= "t.*";

$criteria->group= 't.id';

$criteria->order= '(select count(id) from asset where asset.owner_id=t.user_id and available=0)-(select count(id) from trade where trade.user_id=q.user_id) desc,(select count(id) from asset where asset.owner_id=q.user_id) desc')';

$criteria->condition= 'q.priority=:priority';


for($priority = 1; $priority <= 10; $priority++ ) 

{

   $criteria->params=array(':priority'=>$priority);

   UserQueue::model->findAll($criteria);

   

}






This is just a sample.

Remember that the main table alias is t, the first joined t1 and so on.

Take a look at the documetation of CDbCriteria for more detailed informations.

Thanks for the sample! This got me back on the right track.