简体   繁体   English

如何在yii2中显示相关表格中的数据?

[英]how to display data from related table in yii2?

i got the problem when to display data from related table using yii2. 我在使用yii2显示来自相关表的数据时遇到了问题。 I use my own design and not using from yii2 design. 我使用自己的设计,而不是使用yii2设计。 I have two tables user and 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 UserModel.php

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

UserController.php UserController.php

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

    ]);
}

State.php State.php

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

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

view.php view.php

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

when I use $model->states; 当我使用$ model-> states; I got the error when execute at the browser. 我在浏览器执行时遇到错误。 The error is " Object of class app\\models\\State could not be converted to string ". 错误是“ 类app \\ models \\ State的对象无法转换为字符串 ”。 Before I write that code, I use $model->state_id and the result is number value which is state_id attribute from table state. 在编写该代码之前,我使用$ model-> state_id,结果是数值,即表状态的state_id属性。 What I want is, the name of the state(state attribute from table state),not the state_id. 我想要的是状态的名称(来自表状态的状态属性),而不是state_id。 If using yii2 design, the results will be displayed from what I want. 如果使用yii2设计,结果将根据我的需要显示。 That code its look like this:: 那段代码看起来像这样::

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

    ],
]) ?>  

So, my question is how to recall function getStates() from UserModel.php or getState() from state.php that I created to view.php and display data from related table? 那么,我的问题是如何从UserModel.php中调用函数getStates()或从我创建的state.php调用getState()到view.php并显示相关表中的数据? . sorry, if my english language not very well . 对不起,如果我的英语不太好。

Since $model->states is an object, you should simply use : 由于$model->states是一个对象,你应该简单地使用:

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

And you don't need getState() function in State model. 并且您在状态模型中不需要getState()函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM