[英]how to display relation data into json format from two table in yii2 restful api
我遇到的問題是將兩個表中的數據顯示為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
volunteerController.php
public $modelClass = 'app\models\Volunteer';
public function behaviors()
{
return ArrayHelper::merge(parent::behaviors(),[
'verbs' => [
'class' => VerbFilter::className(),
'actions' => [
'delete' => ['post'],
],
],
]);
}
配置/ web.php
'rules' => [
['class' => 'yii\rest\UrlRule', 'controller' => ['volunteer','state','post']],
],
'request' => [
// !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
'cookieValidationKey' => 'QMoK0GQoN7_VViTXxPdTISiOrITBI4Gy',
'parsers' => [
'application/json' => 'yii\web\JsonParser',
],
],
這是JSON格式的結果:
[
{
"volunteer_id": 1,
"country_id": 1,
"state_id": 12,
}
]
所以結果不是我想要的。 我想要的是state_id應該從表狀態返回狀態數據,這意味着狀態:紐約 。 不返回state_id。 如何解決這個問題呢 ?
public function fields(){
return [
'volunteer_id',
'country_id',
'state' => function ($model) {
return $model->setOtherAttr($model->state_id);
},
'other_attr1',
'other_attr2',
];
}
public function setOtherAttr($state_id){
$state = State::find()->where(['state_id'=>$state_id])->one();
$this->other_attr1 = $state->other_attr1;
$this->other_attr2 = $state->other_attr2;
return $state->state;
}
請嘗試以下代碼:
public function setOtherAttr($state_id){
if (($model = State::find()->where(['state_id'=>$state_id])->all()) !== null) {
return $model;
} else {
return '';
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.