CActiveDataProvider->CListView->Data join trouble

Hi,

I have a table Photo and Message. Photo table has a PK user_id, Message table has this key as a foreign key id_receiver.

I’d like to know how to access column names in a joined table:

  1. controller



$Criteria = new CDbCriteria;

$criteria->alias = 'Photo';

$Criteria->join = 'LEFT JOIN message m on m.id_receiver = Photo.user_id';


$dataProvider=new CActiveDataProvider('Photo', array ( 

  'criteria' => $Criteria,

));


$this->render('messages', array('dataProvider'=>$dataProvider));



  1. view

$this->widget('zii.widgets.CListView', array(

  'dataProvider'=>$dataProvider,

  'itemView'=>'_view',

  'template'=>"{items}\n{pager}",

)); 



  1. _view

<?php

echo $data->image; // working

echo $data->user_id; // working

echo $data->message; //does NOT work - it is a column in a joined table `message`

?>

Thanks!

xsnowy

I think you have not declared a relation in the Photo model. Consider doing the following:




class Photo extends CActiveRecord{

     ....

     public function relations() 

     {

          return array( 

          ... 

              'message'=>array(self::HAS_ONE, 'Message', 'id_receiver'), 

          ... 

          );

      }

      ....

}



Then when you init the CActiveDatProvider just do




$dp = new CActiveDataProvider(Photo::model()->with(array('message')));



If the relations is HAS_MANY then correct above code.

Thanks tydeas_dr.

I have already reclared the relation function as you described, but when trying to access a value in a _view: $data->message is causing this error: Property "Photo.message" is not defined. (I want Message.message)

Thanks for any suggestions!

xsnowy

It is solved. The solution can be found here:

http://www.yiiframework.com/forum/index.php?/topic/15394-cactivedataprovider-and-join/