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是外键

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐