Activerecord Relations And Scopes Issue

Hi,

I’m trying to get a “conversation” activerecord and the last message of this conversation .

I have in Conversation




  public function relations()

  {

     return =  array(

      'messages' => array(self::HAS_MANY, 'Message', 'conversation_id'),

    );

  }



and in Message




  public function scopes()

  {

    return array(

      'sent'=>array(

        'condition'=> $this->getTableAlias().'.status=1',

      ),

      'deleted'=>array(

        'condition'=> $this->getTableAlias().'.status=-1',

      ),

      'draft'=>array(

        'condition'=> $this->getTableAlias().'.status=0',

      ),

      'last'=>array(

        'order'=> $this->getTableAlias().'.created DESC',

        'limit'=>1,

      ),

    );

  }



So i’m trying to get my conversations and the last message like this :




$collection = Conversation::model()->with(array('messages'=>array('scopes'=>array('last'))))->findAll()



also tried witht the together option




$collection = Conversation::model()->with(array('messages'=>array('scopes'=>array('last'),'together'=>false)))->findAll()

$collection = Conversation::model()->with(array('messages'=>array('scopes'=>array('last'),'together'=>true)))->findAll()



but it’s nor working i have error


Property "Conversation.custom_message" is not defined.

when i do


    

foreach( $collection as $c ){

      echo $c->custom_message; 

    }



where custom_message is a message table column.

what is wrong ?

Thanks

What about:


foreach( $collection as $c ){

      echo $c->messages[0]->custom_message; 

    }

Also, for get the last message why not to use another relationship in conversation:


  public function relations()

  {

     return =  array(

       'messages' => array(self::HAS_MANY, 'Message', 'conversation_id'),

      'last_message' => array(self::HAS_ONE, 'Message', 'conversation_id', 'order'=>'created DESC'),

    );

  }

and get the result as:


foreach( $collection as $c ){

      echo $c->last_message->custom_message; 

    }

I agree with this. It’s certainly more readable, and therefore likely more maintainable.

In fact it is already the way i do :




'last_message' => array(self::HAS_ONE, 'Message', 'conversation_id', 'scopes'=>'last')



i was wondering if it was possible using "with" , but it seems not.

thanks to both of you.

You can still use with




$collection = Conversation::model()->with(array('last_message'))->findAll();



Or am I misunderstanding what you’re trying to achieve?