【问题标题】:how to display relation data into json format from two table in yii2 restful api如何在yii2 restful api中将两个表中的关系数据显示为json格式
【发布时间】:2015-08-02 12:30:35
【问题描述】:

我遇到了将两个表中的数据显示为 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'],
            ],
        ],
    ]);
}

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 格式的结果:

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

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

【问题讨论】:

    标签: php json rest yii2 relation


    【解决方案1】:

    这可以通过像这样覆盖 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
            },
        ];
    }
    

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

    官方文档:

    【讨论】:

    • 我不明白'state' => function ($model) { return $model->state->name; // 返回相关模型属性,根据你的结构正确 },这段代码实际放在哪里?
    • 您是否通过我提供的链接阅读了文档?它应该在您的 ActiveRecord 模型中完成。
    • 好的..我明白了。我替换了 return $model->states->state 及其 100% 的工作。谢谢你的关心。
    • 我不使用您提供的文档。我只是创建另一个函数 public function getStates() { return $this->hasOne(State::className(),['state_id'=>'state_id']); }
    • 很高兴为您提供帮助。如果它解决了您的问题,您可以接受答案。
    【解决方案2】:
    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;
    }
    

    【讨论】:

      【解决方案3】:

      试试下面的代码:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-11
        • 1970-01-01
        • 2020-05-24
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多