Returning User via REST API

Hey Guys,

I’m having no luck returning relational objects instead of ID’s.

Inside my REST API




public function actionGetUserContactInfo($id)

{

	$user = User::findOne($id);

	$contact = $user->contact;

	return $contact;

}



In my model:




/**

  * @return \yii\db\ActiveQuery

  */

 public function getContact()

 {

     return $this->hasOne(UserContact::className(), ['id' => 'contact']);

 }




My Response is a 2; Which is the ID of the contact record, but I need the record itself.

Want to point out to avoid confusion and save everyones time:

I have overridden the fields() and extraFields() methods.

Tried the following URL :

afterward

I have since refactored this code and made the following changes.

This is my rest controller action




public function actionGetUserContactInfo($id)

{

	if(!Yii::$app->user->isGuest){

		$user = User::findOne(Yii::$app->user->id);

		$user->contact = $user->contactInfo;

		return $user;

	}


	return null;

}




This is my model relation




/**

  * @return \yii\db\ActiveQuery

  */

 public function getContactInfo()

 {

      return $this->hasOne(UserContact::className(), ['id' => 'contact']);

 }




I also just found this out, and couldn’t find documentation on it anywhere. I have a property called “contact” in my user model, I should probably have called it “contact_id” but I am merely pointing out what happens when I generated my hasOne relation with the GII tool it named it getContact (as it should), however when accessing that relation according to the docs I came across a problem - using $user->contact (assuming to get my relation) i got my property contact and was returning the int (the one that solves my issue above (sorta)).

Now my new issue. I have since renamed my relation to “contactInfo” and it works fine. But as you can see from the code above in my REST controller, I have to first find my user and then query it’s contact information to get the response I am looking for from my API. Is there anyway to do it in 1 query? wherein I can trade my contact id for the corresponding record? I have tried joinWith but it doesn’t seem to work. The above action does now work and returns the data structure I am looking for. I wont mind doing this, I just wanna see if there is a better way to do it.

So to answer / close this thread:

  1. DON’T name your property names the same as any relations [e.g. contact & contact ]. I should have named my property “contact_id” instead of “contact”.

  2. Use active record as stated above. Thanks Cebe!