dpkrbe395930 2017-04-11 10:49
浏览 27
已采纳

Yii2 rest API与用户一起发布

I am creating REST API in YII2. I am getting all post data by calling get API

/post/
/post/1/

But I want to get user also who post that particular post.

for example I want data in below format

{
      "id":"1",
      "title":"kapil",
      "content" : "test",
      "user" : {
         "username":"admin",
         "first_name":"kapil",
         "last_name":"sharma",
          //blah blah
      }

}

But response is

{
          "id":"1",
          "title":"kapil",
          "content" : "test",
}

I used this tutorial for creating API.

  • 写回答

1条回答 默认 最新

  • duanba5777 2017-04-11 11:08
    关注

    Let's say in your post method you have the getIdUser() relation:

    public function getIdUser() {
      return $this->hasOne(User::className(), ['id' => 'user_id']);
    }
    

    In that model, you should make use of the extraFields() method, as follows:

    public function extraFields() {
      return [
        'user' => 'idUser' // or the name you hasOne relation with user has
      ];
    }
    

    Then, you call your REST API with the expand parameter, specifying there which extraField details you'd like to include, in your case:

    http://example.com/post/view?id=1&expand=user

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置