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.