0

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

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

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

4

1 回答 1

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'
            )
        )
于 2013-06-11T18:38:50.227 回答