I am a begginner in the yii framework and I can't find how to show relation in view.
I tried this way:
my model (Cities.php)
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'states' => array(self::BELONGS_TO, 'State', 'state_id')
);
}
My View Code is as below :
<?php
$cities = Cities::model()->findAll();
foreach($cities as $city){
$state=States::model()->findByPk($city->id);?>
<tr>
<td><?php echo cities.state_id;?></td>
</tr>
<?php } ?>
But I am getting error undefined index cities. How can I fix that error?
Replace your code as below :
<?php echo $city.state_id;?></td>
I have replaced cities.state_id to $city.state_id two mistakes as below
$cities and your variable $city is single object.echo cities.state_id as here you have suppose to use $city and also you are not adding $ name for variable.EDIT after reading your comment: Now if you want to show the state name using relation you can do it as below :
<?php echo $city->states->state_name; ?>
where states is a relationship name
This will work:
<?php
$cities = Cities::model()->findAll();
foreach($cities as $city) {
?>
<tr>
<td><?php echo $city->states->state_name;?></td>
</tr>
<?php
}
?>
The model:
public function relations()
{
// NOTE: you may need to adjust the relation name and the related
// class name for the relations automatically generated below.
return array(
'states' => array(self::BELONGS_TO, 'State', 'state_id')
);
}
Here,
states is the relationship name
BELONGS_TO is the relationship type
State is the model it is being connected to
state_id is the foreign key
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With