本文介绍了如何在yii2 restful api中从两个表将关系数据显示为json格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了将两个表中的数据显示为JSON格式并使用yii2 restful api的问题.

I got the problem to display the data from two table into JSON format and working on 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'],
            ],
        ],
    ]);
}

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

    ],

这是JSON格式的结果:

this is the result in JSON format:

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

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

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 ?

推荐答案

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

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

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

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

官方文档:

  • Overriding fields()
  • Customizing actions

这篇关于如何在yii2 restful api中从两个表将关系数据显示为json格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 01:56