xsnowy
(Zbynny)
January 8, 2012, 2:05pm
1
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:
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));
view
$this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'template'=>"{items}\n{pager}",
));
_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
tydeas_dr
(Tydeas Dr)
January 8, 2012, 2:17pm
2
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.
xsnowy
(Zbynny)
January 8, 2012, 2:25pm
3
tydeas_dr:
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
xsnowy
(Zbynny)
January 8, 2012, 2:46pm
4
xsnowy:
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/