Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create and view relation in yii framework for states and cities

Tags:

php

relation

yii

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?

like image 467
Nilisha Avatar asked Dec 10 '25 09:12

Nilisha


2 Answers

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

  1. Your are looping on $cities and your variable $city is single object.
  2. Typo mistake 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

like image 191
Ganesh Ghalame Avatar answered Dec 11 '25 23:12

Ganesh Ghalame


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

like image 39
Criesto Avatar answered Dec 11 '25 22:12

Criesto