Search code examples
yii2yii2-basic-appyii2-module

get nested json object containing all the related data in yii2


I am writing an api to fetch data. I have three models Page , Section and Question.This is image of the erd diagram showing relationship between different entities This is image of the erd diagram showing relationship between different entities.

I have defined there relationships in respective models.

Page Model

class CmsPage extends ActiveRecord
{
    public static function tableName()
    {
         return '{{%cms_page}}';
    }

    public function getCmsSection()
    {
       /*Page and Section has many to many relation having a junction table*/
        return $this->hasMany(CmsSection::className(),['id'=>'section_id'])->viaTable('tbl_cms_page_section',['page_id'=>'id']);
    }
}

Section Model

class CmsSection extends ActiveRecord
{
    public static function tableName()
    {
        return '{{%cms_section}}';
    }

    public function getCmsQuestion()
    {
        return $this->hasMany(CmsQuestion::className(),['id'=>'section_id']);
    }

}

Question Model

class CmsQuestion extends ActiveRecord
{
    public static function tableName()
    {
        return '{{%cms_question}}';
    }

    public function getCmsSection()
    {
        return $this->hasOne(CmsSection::className(),['section_id'=>'id']);
    }
}

I want to fetch data as a json object like below

{
"id": "1",
"name": "Lorem Ipsom",
"title": "Eiusmod voluptate Lorem aute tempor fugiat eiusmod ex ipsum enim magna consequat cupidatat.",
"short_summary": "Will ContentsQuis consequat occaecat consequat aliquip adipisicing aute sunt pariatur culpa sint consectetur reprehenderit eu aliquip.",
"summary": "Officia eu fugiat quis laboris voluptate sunt sint cupidatat eu consequat et deserunt sint eu.",
"section": [
  {
    "id": 1,
    "title": "Advanced Planning",
    "short_summary": "Advanced Planning",
    "summary": "Summary ",
    "question": [
      {
        "id": 1,
        "question_type_id": 1,


        "show_relations": "true",
        "title": "Family Members",
        "place_holder_text": "Your faimly list is currently empty.",

        "label_name": "Name",
        "label_email": "Email",
        "label_phone": "Mobile number",
        "select_1": "url:test-data/dashboard-relationship.json",
        "label": "Remarks"

      },
      {
        "id": 2,
        "question_type_id": 2,


        "title": "Close Friends",
        "place_holder_text": "Your list is close friends currently empty.",

        "label_name": "Name",
        "label_email": "Email",
        "label_phone": "Mobile number",
        "label_address": "Address",
        "help_text": "<b>Close Friends<b><ul><li>1</</li><li>2</</li></ul>"
      },
      {
        "id": 3,
        "question_type_id": 3,

        "title": "Designated Executors",
        "place_holder_text": "It is vital you nominate an Executor",

        "label_name": "Name",
        "label_email": "Email",
        "label_phone": "Mobile number",
        "label_address": "Address"
      },
      {
        "id": 4,
        "question_type_id": 4,
        "question_type": {},
        "title": "Witnesses",
        "place_holder_text": " It is vital you nominate an Executor",
        "label_1": "Name",
        "opption_2": "Email",
        "label_3": "Phone",
        "label_4": "Occupation",
        "label": "Address"
      }
    ]
  },
  {
    "id": 2,
    "title": "Labore proident cupidatat ex dolore occaecat in tempor sit proident sint labore minim cillum.",
    "summary": "Dolor cupidatat consequat cillum deserunt laborum aliqua commodo occaecat sint aute cillum exercitation.",
    "short_summary": "Ullamco Lorem incididunt dolore ipsum.",
    "question": [
      {

        "id": 5,
        "question_type_id": 5,
        "title": "Last Words",
        "short_summary": "Plan, the way you want!",
        "summary": "Start by writing down.",
        "label": "Write your last words here"
      },
      {

        "id": 6,
        "question_type_id": 5,
        "title": "Venue",
        "short_summary": "Plan, the way you want!",
        "summary": "Start by writing down.",
        "label": "Mention"
      }

    ]
  }

]

}

I have followed yii2 docs to come this far but not been able to get data in the json format. How to do that?


Solution

  • HI in API there a function call fields you can override that function :

    Please check below code which will help you to get idea or for more detail you read yii2 doc here Yii 2 fields doc

    public function fields()
    {
        return [
            'id',
            "name"
            'title',
            'short_summary',
            'summary',
            'section'=> function ($model) {
                return $model->cmsSection;
            }, 
        ];
    }
    

    if you want to go more nested then you can use array store first nested data and again use loop for inner data:

    'section'=> function ($model) {
                     $sections =  $model->cmsSection;
                       //store section data in array
                     //forloop of $sections
                      $sections->question;
                    //Again store question data in first array and return it  
                }, 
    

    Aplly it you will understand what i am trying to tell you.