Tuesday, March 15, 2022

[FIXED] How to rename the json array name in cakephp?

Issue

I want to change the json name for below code

For example

     {
        "id": 1,
        "mb_item_list": {
            "item_name": "Something"
        }
    }

Change the code to

{
        "id": 1,
        "name": "Something"

    }

Here I share the Controller code

    if ($this->request->is('get')) {
    $itemname= $this->request->query('item_name');
    $searchitem = $this->MbPriceList->find('all')
                ->contain(['MbItemList' => function ($q) {
                    return $q->select(['item_name']);
                }])
                ->select(['MbItemList.item_name', 'id']);    
     $this->set([
        'response' => $searchitem,
        '_serialize' => ['response']
    ]);
    }

Solution

I think You can use fields inside finder options. Fields allows us to generate aliases for database fields and helps with avoiding nested arrays:

    $searchitem = $this->ModelA->find('all' , [
            'fields' => [
                'id', 
                'name' => 't1.whatever'
            ], 
            'join' => [
                'table' => 'model_b', 
                'alias' => 't1', 
                'type' => 'INNER', 
                'conditions' => [
                    't1.id = ModelA.id'
                ]
            ]
        ])
    ->toArray();

Example output generated with this method:

[  
   {  
      "id":1,
      "name":"Config"
   },
   {  
      "id":2,
      "name":"Dashboard"
   },
   {  
      "id":3,
      "name":"Files"
   }
]


Answered By - Dariusz Majchrzak

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.