2
我在使用yii2顯示相關表中的數據時遇到了問題。我使用我自己的設計,而不是從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>
當我使用$模型 - >狀態
;在瀏覽器中執行時出現錯誤。錯誤是「類app \ models \ State的對象無法轉換爲字符串」。在我編寫代碼之前,我使用$ model-> state_id,結果是數字值,它是表狀態中的state_id屬性。我想要的是,狀態的名稱(來自表狀態的狀態屬性),而不是state_id。如果使用yii2設計,結果將顯示我想要的。該代碼它的外觀這樣的:
<?= DetailView::widget([
'model' => $model,
'attributes' => [
'states.state',
],
]) ?>
所以,我的問題是如何回憶起state.php功能的getStates()從UserModel.php或的getState(),我創建的view.php和顯示數據從相關表格? 。對不起,如果我的英文不太好。
ouh..just就像那樣?爲什麼我不是像你這樣的天才?..嘿..謝謝回答我的問題。 – shahril
** @ shahril **將答案標記爲已接受。 –