How to display relationship data in json format from two tables in yii2 restful api

I had the problem of displaying data from two tables in JSON format and working with yii2 restful api.

this is my database :

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'],
            ],
        ],
    ]);
}

config /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',
                    ],

    ],

this is the result in JSON format:

[
  {
    "volunteer_id": 1,
    "country_id": 1,
    "state_id": 12,
  }
]

so that the result is not what I want. I want state_id to return state data from table state, which means state : New York . Do not return state_id. How to solve this problem?

+4
source share
3 answers

This can be done with an override fields()as follows:

public function fields()
{
    return [
        'volunteer_id',
        'country_id',
        'state' => function ($model) {
            return $model->state->name; // Return related model property, correct according to your structure
        },
    ];
}

In addition, you can look forward to downloading this relationship prepareDataProvider()with with().

:

+5
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;
}
0

Try using the following code:

public function setOtherAttr($state_id){
  if (($model = State::find()->where(['state_id'=>$state_id])->all()) !== null) {
    return $model;
  } else {
   return '';
  }
}
-1
source

Source: https://habr.com/ru/post/1589109/


All Articles