Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to display relation data into json format from two table in yii2 restful api

I got the problem to display the data from two table into JSON format and working on yii2 restful api.

this is my structure 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 result is not what I want. What I want is state_id should return state data from table state which means state : New York . Not return the state_id. How to solve this problem ?

like image 595
shahril Avatar asked Sep 28 '22 21:09

shahril


1 Answers

This can be done with overriding fields() like that:

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

Additionally you can eagerly load this relation in prepareDataProvider() method using with().

Official docs:

  • Overriding fields()
  • Customizing actions
like image 168
arogachev Avatar answered Oct 28 '22 19:10

arogachev