1
votes

in my cakephp 2.0 project i have this model scenario (follow pseudo-code):

model Product {
  int id;
  Video video;
}

model Video {
 ....
}

I want to to use cakephp $this-> Product->find('all') to get all my products and related videos. Cakephp give me the results in a multidimensional array in this way:

{
  Product: {
      id: "3",
      video_id: "1",
  },
  Video: {
      id: "1",
      url: "c",
},
{
  Product: {
      id: "3",
      video_id: "1",
  },
  Video: {
      id: "1",
      url: "c",
}

How can i get the video (child object) inside parent Product, this way:

{
  Product: {
      id: "3",
      video_id: "1",
      Video: {
         id: "1",
         url: "c",
      } 
}

I know that for this particular case its easy to create a new array, because theres only two objects, but is there anyway to make this automatic for bigger relationships, can cakephp handle this?

3
Your scenraio is complete false. You can't put a model class to an other model. Read more: book.cakephp.org/2.0/en/models/… and book.cakephp.org/2.0/en/models/retrieving-your-data.htmlJames Graham
Thank you for response. The code i showed is just pseudo code. In cakephp you need to make relations, but the representation of whats archived by "hasone" and "belongs" to is exactly what i showed. I need this representation (object inside object) because i need to export json for other plataforms (android/ios), and the default archicteture for models in these are child inside parent.Renato Probst
In your example Product belongsTo Video because products table has foreign key. So, Product is a child of Video but not vice versa.bancer
Yes, but anyway i will not have a product inside video, they will be two separate arrays. What im trying to archieve is to have the child array inside parent array, because this is the way OOP works, and i'll deliever json to other plataforms which only work with OOP.Renato Probst

3 Answers

2
votes

Try this approach. Override default find('all'), so that it will accept custom parameter, that will allow reformatting of results. Put this in AppModel, so it is accessible to all models

Edited base on requirement from comment to remove empty associations and joint data for HABTM associations from reformatted result:

class AppModel extends Model
{
    protected function _findAll($state, $query, $results = array())
    {
        if ($state === 'before') {
            return $query;
        }

        if (isset($query['reformat']) && $query['reformat'] === true) {
            foreach ($results as &$_result) {
                reset($_result);
                $modelName = key($_result);
                $modelPart = array_shift($_result);

                if (!empty($query['filter']) && is_array($query['filter'])) {
                    $this->recursive_unset($_result, $query['filter']);
                }

                $_result = array(
                    $modelName => array_merge($modelPart, $_result)
                );
            }
        }

        return $results;
    }

    public function getHabtmKeys() {
        $habtmKeys = array();
        // 1. level inspection
        foreach ($this->hasAndBelongsToMany as $name) {
            $habtmKeys[] = $name['with'];
        }
        // 2. level inspection
        $allAsssoc = array_merge(
            $this->belongsTo,
            $this->hasMany,
            $this->hasOne
        );
        foreach ($allAsssoc as $assocName => $assocVal) {
            foreach ($this->$assocName->hasAndBelongsToMany as $name) {
                $habtmKeys[] = $name['with'];
            }
        }

        return $habtmKeys;
    }

    private function recursive_unset(&$array, $keys_to_remove) {
        foreach ($keys_to_remove as $_key) {
            unset($array[$_key]);
        }

        foreach ($array as $key => &$val) {
            if (is_array($val)) {
                if (empty($val) || (!isset($val[0]) && empty($val['id']))) {
                    unset($array[$key]);
                } else {
                    $this->recursive_unset($val, $keys_to_remove);
                }
            }
        }
    }
}

To remove empty associations and HABTM joint data, i used recursive unset procedure combined with inspection of associations for relevant model. I was not able to achieve this with configuration of find, contain or any other way.

Next array_shift($_result) divides $_result array into two parts - main model on which a find was run (it is always the first key in result) and the rest (all associations), then it merges these arrays under the key of main model. Of course, this reformats the results only on the first level, but on deeper levels are associations nested by default, so you don't need to care about it.

Now use find('all') as always, but provide custom reformat and filter parameters. If you do not provide them, the result will be fetched in default format.

  • filter is array of keys to be removed from result

  • getHabtmKeys() dynamically gets array of keys of HABTM associations for model (only 1. and 2. level associations, can be further modified to inspect even deeper).

Usage:

// To nest child associations in parent
$this->Product->find('all', array(
    'reformat' => true
));
// To remove also joint data for HABTM and empty associations
$this->Product->find('all', array(
    'reformat' => true,
    'filter' => $this->Product->getHabtmKeys(),        
));
// Keys to remove can be also manually added 
$this->Product->find('all', array(
    'reformat' => true,
    'filter' => array_merge($this->Product->getHabtmKeys(), 'SomeExtraKey'),
));

See also: Retrieving Your Data > Creating custom find types

2
votes

This will work to get each Video child in each Product in the findall

$products = $this->Product->find('all') 

foreach($products as $product) {
  echo $product["Video"]["url"];
}
2
votes

The way Cake returns the object is correct as it is accessing the join and returning the data inside the main find object.

The object inside an object you are talking about happens if you have a deeper level of recursion or you use containable to access deeper relationships.

For example

$this->Product->find('all');

Would return a object like

array(
  'Product' => array(
    'id' => '3',
    'video_id' => '1',
  ),
  'Video' => array(
    'id' => '1',
    'url' => c,
  ),
)

The object layout your are after only happens if there is a hasMany or HABTM join on that Model or you change the level or use containable to then look into the relationships for joined model.

I hope that made sense.