简体   繁体   English

Yii2 Rest API与用户分享

[英]Yii2 rest API get post with user

I am creating REST API in YII2 . 我正在YII2创建REST API。 I am getting all post data by calling get API 我通过调用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. 我使用教程来创建API。

Let's say in your post method you have the getIdUser() relation: 假设在您的post方法中,您具有getIdUser()关系:

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

In that model, you should make use of the extraFields() method, as follows: 在该模型中,应使用extraFields()方法,如下所示:

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: 然后,使用expand参数调用REST API,在这种情况下,指定要包含的extraField详细信息:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM