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

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

但是我得到了未定义索引城市的错误.我该如何解决该错误?

解决方法:

这将起作用:

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

这里,

状态是关系名称

BELONGS_TO是关系类型

状态是它所连接的模型

state_id是外键

上一篇:如何用 Python 发送告警通知到微信?


下一篇:【雅思】雅思核心词汇精讲-unit 1