inverseOf and relations in returned data


(Y Korotia) #1

I have problem with returned object in REST controller.

I have 2 AR : User and Salary. User has relation to salary as hasOne() with inverseOf. And Salary hasOne() to User.

PROBLEM #1 - Where is Salary in response?




// REST controller from yii\rest\ActiveController


    public function actionUser() {

        $user = User::find()->with('salary')->one();

        return $user;

    }




<response>

    <id>1</id>

    <username>root</username>

    <auth_key>...</auth_key>

    <password_hash>...</password_hash>

    <password_reset_token />

    <email>...</email>

<----- WHERE IS <salary> ?

    <status>10</status>

    <created_at>1502204969</created_at>

    <updated_at>1502204969</updated_at>

</response>



Sure, I can return as array, but why?

PROBLEM #2 - inverseOf returns also user object. How can I avoid this?

Assume I gave up with object return and use array, now


// REST controller from yii\rest\ActiveController


    public function actionUsers() {

        $user = User::find()->with('salary')->asArray()->one();

        return $user;

    }




<response>

    <id>1</id>

    <username>root</username>

    <auth_key>..</auth_key>

    <password_hash>...</password_hash>

    <password_reset_token />

    <email>...</email>

    <status>10</status>

    <created_at>1502204969</created_at>

    <updated_at>1502204969</updated_at>

    <salary>

        <id>1</id>

        <user_id>1</user_id>

        <salary>1000</salary>

        <user>  <----------- I DONT NEED THIS!

            <id>1</id>

            <username>root</username>

            <auth_key>...</auth_key>

            <password_hash>...</password_hash>

            <password_reset_token />

            <email>...</email>

            <status>10</status>

            <created_at>1502204969</created_at>

            <updated_at>1502204969</updated_at>

            <salary>

                <id>1</id>

                <user_id>1</user_id>

                <salary>1000</salary>

                <user />

            </salary>

        </user>

    </salary>

</response>



regards


(Y Korotia) #2

got it done by adding to User AR


    public function fields()

    {

        return array_merge(parent::fields(), ['salary']);

    }

weird