0

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.

2
  • where is your code?? Commented Apr 11, 2017 at 10:50
  • I just create controller and rest of the work is done by default Yii2 REST API format Commented Apr 11, 2017 at 10:51

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

How can i create a relation. I am new in Yii

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.