Display Active Record result

I’m having a hard time finding anything in the documentation to show how to display a single result from using find().

I found the following code:


<?php echo CHtml::activeDropDownList($model, 'catid', CHtml::listData(

 Category::model()->findAll(), 'id', 'catname'

 )

 ); ?>

And it works perfectly. But it displays a dropdown menu when I only want to show a single text result, so I tried this:


<?php echo Category::model()->find(array(

                    'select'=>'catname',

                    'condition'=>'catid=:catid',

                    'params'=>array(':catid'=>'42'),

                ));

        ?>

But get the error: Object of class Category could not be converted to string

How can this be done? Am I doing find() the right way?

Hi skyer,

find() returns a record not a single value/string. It’s like a row of the table. So if you want to output a value of this row you’ll need to select it s.th. like


<?php $model = Category::model()->find(array(

                    'select'=>'catname',

                    'condition'=>'catid=:catid',

                    'params'=>array(':catid'=>'42'),

                ));

      echo $model->catname;

        ?>

See, you get the record matching your conditions etc. and you have to pick the single value you would like to display, use or whatever. In the example above the value of ‘catname’ of the record with catid = 42 is echoed.

Regards

From a performance standpoint would it make more sense to only pull the value we want instead of the entire row? Is that possible?

For consistency, it’s worth retrieving the row object. The overhead is small enough. Have you got some more context so we can make a better assessment? How many times will this be repeated on a page?

@skyer200:

If performance becomes an issue, you can switch back to DAO for such simple queries. No AR overhead involved, you get a clean result array. There’s nothing wrong to put such a method inside the Category model:


public function queryNames($catid) {

    $sql='SELECT catname FROM category WHERE catid=:catid';

    return Yii::db()->createCommand($sql)->queryColumn(array(':catid'=>$catid));

}