如何在州和城市的 yii 框架中创建和查看关系

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

我是 yii 框架的初学者,我找不到如何在视图中显示关系。

我这样试过:

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')
            );
        }

我的查看代码如下:

<?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 } ?>

但我得到 error undefined index cities。我该如何修复该错误?

按以下方式替换您的代码:

<?php echo $city.state_id;?></td>

我已经将 cities.state_id 替换为 $city.state_id 两个错误如下

  1. 您正在 $cities 上循环并且您的变量 $city 是单个对象。
  2. 打字错误 echo cities.state_id 因为这里你假设使用 $city 而且你没有为变量添加 $ 名称。

阅读您的评论后进行编辑: 现在,如果您想使用关系显示州名,您可以按如下方式进行:

<?php echo $city->states->state_name; ?>

其中 states 是关系名称

这会起作用:

<?php
$cities = Cities::model()->findAll();
foreach($cities as $city) {
?>
<tr>
    <td><?php echo $city->states->state_name;?></td>
</tr>
<?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')
            );
        }

这里,

states是关系名

BELONGS_TO是关系类型

State 是它正在连接的模型

state_id是外键