doupang3062 2015-01-07 13:08
浏览 6
已采纳

在cakephp找到的父母内部的子关系对象

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条回答 默认 最新

  • doufenyu7610 2015-05-15 23:28
    关注

    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条)

报告相同问题?

悬赏问题

  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊
  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘