我在使用 yii2 显示相关表中的数据时遇到了问题。我使用自己的设计而不是使用 yii2 设计。 我有两个表 user 和 state
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_id 属性。我想要的是状态的名称(来自表状态的状态属性),而不是 state_id。如果使用 yii2 设计,结果将显示为我想要的。该代码看起来像这样::
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'states.state',
],
]) ?>
所以,我的问题是如何从我创建的 UserModel.php 中调用函数 getStates() 或从 state.php 中调用 getState() 到 view.php 并显示相关表中的数据? .抱歉,如果我的英语不是很好。
最佳答案
因为 $model->states
是一个对象,你应该简单地使用:
<?= $model->states->state ?>
而且您不需要状态模型中的 getState()
函数。
关于php - 如何在 yii2 中显示相关表中的数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29486140/