PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, March 15, 2022

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

 March 15, 2022     cakephp, cakephp-3.0     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing