Displaying category name based on category id...

It works for me, but i’m just wondering if i’m doing it correctly and if there’s a simpler way.

There are 2 tables…

ITEM with "category_id" among numerous other fields.

CATEGORY with "id" and "name" fields.

My Item controller has the following relation defined…

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

My Item view translates stored "category_id" to its actual "name" from the CATEGORY table like this…

<?php if (isset($model->category)) echo CHtml::encode($model->category->name); ?>

Since category is always required and not null, i’m thinking of omitting “if (isset($model->category))” to make things more compact.

Is there a better way? reason i’m asking is because my item will have about 5 different numeric fields and i’ll need to associate them with values stored in 5 different tables. Do i need to set FK for each of those different fields or not?

Anyone?

Since an item cannot exist without a parent category in theory, the condition should be omitted as you have thought.

Make sure you specify the relations in the call to with() so database won’t be queried in each iteration.

Please let me know what do you mean by "with()"?

In your action $model is defined for sure. Before call to findAll() you should put a call to with() as well specifying all relations that should be accessible from your view.