我在使用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
Run Code Online (Sandbox Code Playgroud)
UserModel.php
public function getStates()
{
return $this->hasOne(State::className(),['state_id' =>'state_id']);
}
Run Code Online (Sandbox Code Playgroud)
UserController.php
public function actionView($id)
{
return $this->render('view', [
'model' => $this->findModel($id),
]);
}
Run Code Online (Sandbox Code Playgroud)
State.php
public function attributeLabels()
{
return [
'state_id' => 'State ID',
'state' => 'State',
];
}
public function getState()
{
return $this->state.'';
}
Run Code Online (Sandbox Code Playgroud)
view.php
<table>..<tr>
<td>Negeri</td>
<td><?php echo $model->states; ?></td>
</tr>
Run Code Online (Sandbox Code Playgroud)
当我使用$ model-> states; …
我遇到的问题是将两个表中的数据显示为JSON格式并处理yii2 restful api.
这是我的结构数据库:
TABLE `volunteer`(
`volunteer_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
Run Code Online (Sandbox Code Playgroud)
volunteerController.php
public $modelClass = 'app\models\Volunteer';
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(),[
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
]);
}
Run Code Online (Sandbox Code Playgroud)
配置/ web.php
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['volunteer','state','post']],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) …Run Code Online (Sandbox Code Playgroud)