我在使用yii2显示相关表中的数据时遇到了问题。我使用我自己的设计,而不是使用来自yii2的设计。我有两个表用户和状态
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时;我在浏览器上执行时出错。错误为"类app''models''State的对象无法转换为字符串"。在编写代码之前,我使用$model->state_id,结果是数值,它是来自表state的state_id属性。我想要的是状态的名称(表state中的state属性),而不是state_id。如果使用yii2设计,结果将根据我的要求显示。这个代码看起来是这样的::
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'states.state',
],
]) ?>
所以,我的问题是如何从UserModel.php中调用函数getStates(),或者从我创建的state.php中调用getState()来查看.php并显示相关表中的数据。对不起,如果我的英语不太好的话。
由于$model->states
是一个对象,您应该简单地使用:
<?= $model->states->state ?>
并且在状态模型中不需要getState()
函数。