如何在yii2 restful api中从两个表中将关系数据显示为json格式

sha*_*ril 4 php rest json relation yii2

我遇到的问题是将两个表中的数据显示为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) - this is required by cookie validation
        'cookieValidationKey' => 'QMoK0GQoN7_VViTXxPdTISiOrITBI4Gy',
                    'parsers' => [
                    'application/json' => 'yii\web\JsonParser',
                    ],

    ],
Run Code Online (Sandbox Code Playgroud)

这是JSON格式的结果:

[
  {
    "volunteer_id": 1,
    "country_id": 1,
    "state_id": 12,
  }
]
Run Code Online (Sandbox Code Playgroud)

所以结果不是我想要的.我想要的是state_id应该从表状态返回状态数据,这意味着状态:纽约.不返回state_id.如何解决这个问题呢 ?

aro*_*hev 5

这可以通过覆盖来完成fields():

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

此外,您可以在prepareDataProvider()方法中急切地加载此关系with().

官方文档: