cakephpcakephp-2.6

After using Set::extract not getting associative data


I am trying to get json data without model name, so here I have tried extract like below code

$transaction = $this->Transaction->find('all', array('conditions'=>array('Transaction.user_id'=>$id)));
$transaction = Set::extract('/Transaction/.', $transaction);

Problem is now I am not getting associative data in json output. Here is the json look like

[{"id":"130","transaction_type":"1","user_id":"44","entry_by":"pitocms","added_id":"25","perticuler":"test","Volume":null,"per_unit":null,"credit_money":"1500","debit_money":"0","balance":"-1500","created":"2015-12-27 21:21:11","modified":"2015-12-27 21:21:11"}]

There has actually 2 model transaction and user.


Solution

  • Set::extract() does exactly that, it creates a new array after extracting selected data from a source array. Therefore, in order to obtain user information, you will have to extract it too:

    $data = $this->Transaction->find('all',array('conditions'=>array('Transaction.user_id'=>$id)));
    $transactions = Set::extract('/Transaction/.', $data);
    $users = Set::extract('/User/.', $data);
    

    As stated by @ndm in the comments, class Set has been long deprecated in favour of class Hash. You can achieve the same with:

    $data = $this->Transaction->find('all', array('conditions'=>array('Transaction.user_id'=>$id)));        
    $transactions = Hash::extract($data,'{n}.Transaction');
    $users = Hash::extract($data,'{n}.User');