Return Model with relashions (Restful API)

Hi all. I built few API using Yii2 and all works well, but I have one small issue.


Quest::find()

->with(['images', 'route'])

->all();

Return only Quest object as endpoint JSON response, without images and route.

We can fix it by added asArray():


Quest::find()

->with(['images', 'route'])

->asArray()

->all();

This response will contain quests with images and route. But it’s a bad way, because using asArray() we lost some ActiveRecord features (eg, afterFind).

So how we can solve this please?

Use joinWith instead of with.

http://www.yiiframework.com/doc-2.0/yii-db-activequerytrait.html#with()-detail

http://www.yiiframework.com/doc-2.0/yii-db-activequery.html#joinWith()-detail

Thanks, but:




Quest::find()

->with('images')

->all();



and




Quest::find()

->joinWith('images')

->all();



returns the same result, var_dump:




array(1) {

  [0]=>

  object(common\models\Quest)#59 (9) {

    ["icon_url"]=>

    string(55) "http://website.com/uploads/quests-icons/dsaDWQDS23Dsass.jpg"

    ["_attributes":"yii\db\BaseActiveRecord":private]=>

    array(10) {

      ["id"]=>

      int(1)

      ["region_id"]=>

      int(1)

      ["title"]=>

      string(15) "test ttile"

      ["icon"]=>

      string(19) "dsaDWQDS23Dsass.jpg"

      ["color"]=>

      string(5) "green"

      ["time"]=>

      string(9) "About 1hr"

      ["about"]=>

      string(246) "Non aliquip quis deserunt esse do labore do laboris. Consectetur incididunt cillum est mollit reprehenderit id velit aliquip do esse non. Tempor ullamco sint non est. Id ullamco anim ut sunt proident duis. Magna ad consequat sint magna cupidatat."

      ["published"]=>

      int(1)

      ["created_at"]=>

      string(19) "2015-09-02 00:00:00"

      ["updated_at"]=>

      string(19) "2015-09-07 09:46:58"

    }

    ["_oldAttributes":"yii\db\BaseActiveRecord":private]=>

    array(10) {

      ["id"]=>

      int(1)

      ["region_id"]=>

      int(1)

      ["title"]=>

      string(15) "test ttile"

      ["icon"]=>

      string(19) "dsaDWQDS23Dsass.jpg"

      ["color"]=>

      string(5) "green"

      ["time"]=>

      string(9) "About 1hr"

      ["about"]=>

      string(246) "Non aliquip quis deserunt esse do labore do laboris. Consectetur incididunt cillum est mollit reprehenderit id velit aliquip do esse non. Tempor ullamco sint non est. Id ullamco anim ut sunt proident duis. Magna ad consequat sint magna cupidatat."

      ["published"]=>

      int(1)

      ["created_at"]=>

      string(19) "2015-09-02 00:00:00"

      ["updated_at"]=>

      string(19) "2015-09-07 09:46:58"

    }

    ["_related":"yii\db\BaseActiveRecord":private]=>

    array(1) {

      ["images"]=>

      array(1) {

        [0]=>

        object(common\models\ImageQuest)#80 (9) {

          ["url"]=>

          string(58) "http://website.com/uploads/images-quests/asdDW-qedq2_dsaww.png"

          ["_attributes":"yii\db\BaseActiveRecord":private]=>

          array(5) {

            ["id"]=>

            int(1)

            ["quest_id"]=>

            int(1)

            ["filename"]=>

            string(21) "asdDW-qedq2_dsaww.png"

            ["created_at"]=>

            string(19) "2015-09-03 00:00:00"

            ["updated_at"]=>

            string(19) "2015-09-03 00:00:00"

          }

          ["_oldAttributes":"yii\db\BaseActiveRecord":private]=>

          array(5) {

            ["id"]=>

            int(1)

            ["quest_id"]=>

            int(1)

            ["filename"]=>

            string(21) "asdDW-qedq2_dsaww.png"

            ["created_at"]=>

            string(19) "2015-09-03 00:00:00"

            ["updated_at"]=>

            string(19) "2015-09-03 00:00:00"

          }

          ["_related":"yii\db\BaseActiveRecord":private]=>

          array(0) {

          }

          ["_errors":"yii\base\Model":private]=>

          NULL

          ["_validators":"yii\base\Model":private]=>

          NULL

          ["_scenario":"yii\base\Model":private]=>

          string(7) "default"

          ["_events":"yii\base\Component":private]=>

          array(2) {

            ["beforeInsert"]=>

            array(1) {

              [0]=>

              array(2) {

                [0]=>

                array(2) {

                  [0]=>

                  object(yii\behaviors\TimestampBehavior)#82 (5) {

                    ["createdAtAttribute"]=>

                    string(10) "created_at"

                    ["updatedAtAttribute"]=>

                    string(10) "updated_at"

                    ["value"]=>

                    object(yii\db\Expression)#81 (2) {

                      ["expression"]=>

                      string(5) "NOW()"

                      ["params"]=>

                      array(0) {

                      }

                    }

                    ["attributes"]=>

                    array(2) {

                      ["beforeInsert"]=>

                      array(2) {

                        [0]=>

                        string(10) "created_at"

                        [1]=>

                        string(10) "updated_at"

                      }

                      ["beforeUpdate"]=>

                      string(10) "updated_at"

                    }

                    ["owner"]=>

                    *RECURSION*

                  }

                  [1]=>

                  string(18) "evaluateAttributes"

                }

                [1]=>

                NULL

              }

            }

            ["beforeUpdate"]=>

            array(1) {

              [0]=>

              array(2) {

                [0]=>

                array(2) {

                  [0]=>

                  object(yii\behaviors\TimestampBehavior)#82 (5) {

                    ["createdAtAttribute"]=>

                    string(10) "created_at"

                    ["updatedAtAttribute"]=>

                    string(10) "updated_at"

                    ["value"]=>

                    object(yii\db\Expression)#81 (2) {

                      ["expression"]=>

                      string(5) "NOW()"

                      ["params"]=>

                      array(0) {

                      }

                    }

                    ["attributes"]=>

                    array(2) {

                      ["beforeInsert"]=>

                      array(2) {

                        [0]=>

                        string(10) "created_at"

                        [1]=>

                        string(10) "updated_at"

                      }

                      ["beforeUpdate"]=>

                      string(10) "updated_at"

                    }

                    ["owner"]=>

                    *RECURSION*

                  }

                  [1]=>

                  string(18) "evaluateAttributes"

                }

                [1]=>

                NULL

              }

            }

          }

          ["_behaviors":"yii\base\Component":private]=>

          array(1) {

            [0]=>

            object(yii\behaviors\TimestampBehavior)#82 (5) {

              ["createdAtAttribute"]=>

              string(10) "created_at"

              ["updatedAtAttribute"]=>

              string(10) "updated_at"

              ["value"]=>

              object(yii\db\Expression)#81 (2) {

                ["expression"]=>

                string(5) "NOW()"

                ["params"]=>

                array(0) {

                }

              }

              ["attributes"]=>

              array(2) {

                ["beforeInsert"]=>

                array(2) {

                  [0]=>

                  string(10) "created_at"

                  [1]=>

                  string(10) "updated_at"

                }

                ["beforeUpdate"]=>

                string(10) "updated_at"

              }

              ["owner"]=>

              *RECURSION*

            }

          }

        }

      }

    }

    ["_errors":"yii\base\Model":private]=>

    NULL

    ["_validators":"yii\base\Model":private]=>

    NULL

    ["_scenario":"yii\base\Model":private]=>

    string(7) "default"

    ["_events":"yii\base\Component":private]=>

    array(2) {

      ["beforeInsert"]=>

      array(1) {

        [0]=>

        array(2) {

          [0]=>

          array(2) {

            [0]=>

            object(yii\behaviors\TimestampBehavior)#64 (5) {

              ["createdAtAttribute"]=>

              string(10) "created_at"

              ["updatedAtAttribute"]=>

              string(10) "updated_at"

              ["value"]=>

              object(yii\db\Expression)#61 (2) {

                ["expression"]=>

                string(5) "NOW()"

                ["params"]=>

                array(0) {

                }

              }

              ["attributes"]=>

              array(2) {

                ["beforeInsert"]=>

                array(2) {

                  [0]=>

                  string(10) "created_at"

                  [1]=>

                  string(10) "updated_at"

                }

                ["beforeUpdate"]=>

                string(10) "updated_at"

              }

              ["owner"]=>

              *RECURSION*

            }

            [1]=>

            string(18) "evaluateAttributes"

          }

          [1]=>

          NULL

        }

      }

      ["beforeUpdate"]=>

      array(1) {

        [0]=>

        array(2) {

          [0]=>

          array(2) {

            [0]=>

            object(yii\behaviors\TimestampBehavior)#64 (5) {

              ["createdAtAttribute"]=>

              string(10) "created_at"

              ["updatedAtAttribute"]=>

              string(10) "updated_at"

              ["value"]=>

              object(yii\db\Expression)#61 (2) {

                ["expression"]=>

                string(5) "NOW()"

                ["params"]=>

                array(0) {

                }

              }

              ["attributes"]=>

              array(2) {

                ["beforeInsert"]=>

                array(2) {

                  [0]=>

                  string(10) "created_at"

                  [1]=>

                  string(10) "updated_at"

                }

                ["beforeUpdate"]=>

                string(10) "updated_at"

              }

              ["owner"]=>

              *RECURSION*

            }

            [1]=>

            string(18) "evaluateAttributes"

          }

          [1]=>

          NULL

        }

      }

    }

    ["_behaviors":"yii\base\Component":private]=>

    array(1) {

      [0]=>

      object(yii\behaviors\TimestampBehavior)#64 (5) {

        ["createdAtAttribute"]=>

        string(10) "created_at"

        ["updatedAtAttribute"]=>

        string(10) "updated_at"

        ["value"]=>

        object(yii\db\Expression)#61 (2) {

          ["expression"]=>

          string(5) "NOW()"

          ["params"]=>

          array(0) {

          }

        }

        ["attributes"]=>

        array(2) {

          ["beforeInsert"]=>

          array(2) {

            [0]=>

            string(10) "created_at"

            [1]=>

            string(10) "updated_at"

          }

          ["beforeUpdate"]=>

          string(10) "updated_at"

        }

        ["owner"]=>

        *RECURSION*

      }

    }

  }

}



So they both contain images:




["_related":"yii\db\BaseActiveRecord":private]=>

    array(1) {

      ["images"]=>

...



But when we return this result in yii\rest\ActiveController we get as JSON response:




{

id: 1

region_id: 1

title: "test ttile"

icon: "dsaDWQDS23Dsass.jpg"

color: "green"

time: "About 1hr"

about: "Non aliquip quis deserunt esse do labore do laboris. Consectetur incididunt cillum est mollit reprehenderit id velit aliquip do esse non. Tempor ullamco sint non est. Id ullamco anim ut sunt proident duis. Magna ad consequat sint magna cupidatat."

published: 1

created_at: "2015-09-02 00:00:00"

updated_at: "2015-09-07 09:46:58"

icon_url: "http://website.com/uploads/quests-icons/dsaDWQDS23Dsass.jpg"

}



No images array. Could you please help with that?

p.s. as I mentioned, ->asArray() can fix this, and we receive JSON response with images, but we lost AR features.

I found the solution.

In the Model class to method fields() we should add the names of relations. So joinWith() or with() - doesn’t matter.

So code will be:




    public function fields()

    {

        $fields = parent::fields();


        if($this->isRelationPopulated('images')) {

            $fields['images'] = function ($model) {

                return $model->images;

            };

        }


        return $fields;

    }



Does anyone have any better solution? It’s a bunch of extra code, I would like to avoid that.

It’s all about function toArray(), we have to list the field for it. Then toArray() automatically calls when we return the value in the yii\rest\ActiveController

But I think Yii2 should automatically do this, if we used eager loading (with(), joinWith(), eg.)