Unable to display related field in view

I have 2 tables

category table

id

description

content table

id

category_id (foreign key)

content

What I want to do is display the description instead of the category_id in the content view. What I tried to do is use the find method to extract the description column and then display it.

in content model:




 public function getCategory($category_id)

	{

   //this function returns the description field from one record

   $criteria = new CDbCriteria;

   $criteria->select='description';  // only select the 'description' column

   $criteria->condition='id='. $category_id;

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

   return Category::model()->find($criteria);

  

 }



in the view file:




<?php echo CHtml::encode($data->getCategory($data->category_id)); ?>



The error message I am getting when I try to display the view file:

"htmlspecialchars() expects parameter 1 to be string, object given"

Is there another way I should be trying to display the information returned from my function instead of Chtml::encode or is my function designed incorrectly?

Thanks in advance.

Php says you that it expected string but u gave him object instead of string.


$data->getCategory($data->category_id)

returns object.

so you should write like that:


echo CHtml::encode($data->getCategory($data->category_id)->attrName);

Hi, thanks for the reply. I tried this:




<?php echo CHtml::encode($data->getCategory($data->category_id)->description); ?>



But it is still just showing the category_id, not the description (attribute name). Any other ideas?

why not make use of ‘relations’? Define a relation in Content Model, as such


'category'=>array(self::BELONGS_TO, 'Category', 'category_id');

now, in view file, simply try,


echo $data->category->description;

you can read about relations here