如何在 yii2 中显示来自相关 table 的数据?

how to display data from related table in yii2?

我在使用 yii2 显示来自相关 table 的数据时遇到了问题。我使用自己的设计而不是使用 yii2 设计。 我有两个 tables userstate

TABLE `user`(
`user_id` int(11) NOT NULL auto_increment,
`state_id` int(11) null 

table `state`(
`state_id` int(11) NOT NULL auto_increment,
`state` varchar(225) null

UserModel.php

public function getStates()
{
    return $this->hasOne(State::className(),['state_id' =>'state_id']);
}

UserController.php

 public function actionView($id)
{
    return $this->render('view', [
        'model' => $this->findModel($id),

    ]);
}

State.php

 public function attributeLabels()
{
    return [
        'state_id' => 'State ID',
        'state' => 'State',
     ];
}

public function getState()
{
    return $this->state.'';
}

view.php

<table>..<tr>
    <td>Negeri</td>
    <td><?php echo $model->states; ?></td>
</tr>

当我使用 $model->states;在浏览器上执行时出现错误。错误是“ class app\models\State 的对象无法转换为字符串 ”。在我编写该代码之前,我使用 $model->state_id 结果是数字值,它是来自 table 状态的 state_id 属性。我想要的是状态名称(来自 table 状态的状态属性),而不是 state_id。如果使用 yii2 设计,结果将显示为我想要的。该代码看起来像这样::

<?= DetailView::widget([
    'model' => $model,
    'attributes' => [
        'states.state',

    ],
]) ?>  

所以,我的问题是如何从 UserModel.php 中调用函数 getStates() 或从 state.php 中调用函数 getState() 到 view.php 并显示来自相关 [=57] 的数据=]? .对不起,如果我的英语不是很好。

因为 $model->states 是一个对象,你应该简单地使用 :

<?= $model->states->state ?>

并且您不需要 getState() 状态模型中的函数。