Reputation: 2487
I think I'm kinda confused, I have a model whose some of the fields where to reference their detail/s (description/s) from another table.
eg.
**tblCustomers**
_______________________
Name | Address | Gender
-----------------------
A | A | M
B | B | M
C | C | F
**tblGender**
__________________
Code | Description
------------------
M | Male
F | Female
In my view here's how it look
Name A
Address A
Gender M <<< wherein what I wanted is something like
Name A
Address A
Gender M - Male
In my model, I am currently just doing something like these:
public function search($_id,$_curLevel)
{
// @todo Please modify the following code to remove attributes that should not be searched.
$criteria=new CDbCriteria;
$criteria->compare('Name',$this->name);
$criteria->compare('Address',$this->address);
$criteria->compare('Gender',$this->gender,true);
}
I know its pretty obvious, since the model is just looking into a single table, but I can't figure how to relate and use another table to be able to get the description from other reference tables.
Upvotes: 0
Views: 223
Reputation: 196
If you just wanna the gender description then you can user the relation and display $model->gender->description; as descriped in the above answer If you wanna a custom text as you mentioned "M - Male" then you have to add a public property and fill it in the afterFind() method
class Customer extends CActiveRecord {
public $_gender;
public function afterFind() {
$this->_gender = $this->gender . ' - ' . $this->gender->description;
return parent::afterFind();
}
}
note: that gender relation must be exist
Upvotes: 0
Reputation: 121
The way I would do this, is to add a relation to my model.
I am assuming you have a model setup for the gender table, and it is called Gender. I would also rename your 'gender' column in your customer table to genderID or similar. I have renamed it for my example.
Add this code to your Customer Model:
public function relations()
{
return array(
'gender' => array(self::BELONGS_TO, 'Gender', 'genderID'),
);
}
Then once you have created this relationship, it is very easy to extract the information in your view.
You already have the model, so now the view looks like this:
echo $model->name;
echo $model->address;
echo $model->gender->description;
Note that 'gender' in the line above is referring to the 'gender' relation we created, not the column that you had named 'gender' in the description table (I renamed that to genderID).
Upvotes: 1