查找('threaded')发布版本

时间:2013-06-11 04:19:12

标签: php cakephp cakephp-2.0

我正在构建一个允许上传多个版本的应用程序。树行为是管理它的最佳方式吗?

$allAssets = $this->Asset->find('threaded',  array('order' => array('id' => 'desc')));
    foreach ($allAssets as $asset):
        echo $asset['children'][0]['Asset']['value']; 
    endforeach;

目标是获取每个资产的最新版本的价值。如果没有孩子,我该怎么办?是否有更好的方法来为资产版本提取嵌套数组?

1 个答案:

答案 0 :(得分:0)

您可能希望查看可包含的行为

假设您在资产模型中有以下设置

public $belongsTo = array(
    'ParentAsset' => array(
        'className' => 'Asset',
        'foreignKey' => 'parent_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
)

public $hasMany = array(
    'ChildAsset' => array(
        'className' => 'Asset',
        'foreignKey' => 'parent_id',
        'dependent' => true,
        'conditions' => '',
        'fields' => '',
        'order' => 'created ASC'
    )
);

然后,您将在AssetsController中加载可包含的行为,如此

$this->Asset->Behaviors->load('Containable',array('autoFields' => false));

然后像这样执行你的发现

$this->Asset->find('all',  array(
    'order' => array (
        'id' => 'desc'
        ),
    'contain' => array(
        'ChildAsset' => array(
            'fields' => 'ChildAsset.value',
            'order' => 'ChildAsset.created asc'
    )
    )
);

此find方法应返回格式为

的数组
array(
    (int) 0 => array(
        'Asset' => array(
            'name' => 'assetVersion1',
            'id' => '1234'
        ),
        'ChildAsset' => array(
            (int) 0 => array(
                'name' => 'assetVersion2',
                'id' => '2222',
                'parent_id' => '1234',
                'created' => '2013-06-10 12:00:00'
            )
            (int) 1 => array(
                'name' => 'assetVersion3',
                'id' => '3333'
                'parent_id' => '1234'
                'created' => '2013-06-10 12:30:00'
            )
        )