i got the problem when to display data from related table using yii2. I use my own design and not using from yii2 design. 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
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>
when I use $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 ". Before I write that code, I use $model->state_id and the result is number value which is state_id attribute from table state. What I want is, the name of the state(state attribute from table state),not the state_id. If using yii2 design, the results will be displayed from what I want. 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? . sorry, if my english language not very well .
Since $model->states
is an object, you should simply use :
<?= $model->states->state ?>
And you don't need getState()
function in State model.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.