与hasMany关系中的Paginate相关数据

时间:2013-04-11 16:17:29

标签: cakephp cakephp-2.3 paginate

我在尝试以hasMany关系分页相关数据时遇到了一些麻烦

我有两个模型 - Collection和Item 集合hasMany Item Item belongsTo Collection

在Collection view.ctp中,它显示了传递的ID的集合详细信息以及Items的相关数据。它从查找“第一次”调用中接收此数据。

$this->set('collection', $this->Collection->find('first', $options));

结果数组看起来像:

array(
    'Collection' => array(
        'id' => '4fc923f5-0a58-453f-9507-0c0c86106d80',
        'name' => '<collection_name>'
    ),

    'Item' => array(
        (int) 0 => array(
            'id' => '4fc92403-000c-4ed2-9dae-0c0c86106d80',
            'name' => 'Item1'
        ),
        (int) 1 => array(
            'id' => '4fc9241b-35ec-4810-b511-0c0c86106d80',
            'name' => 'Item2'
        ),
        (int) 2 => array(
            'id' => '4fc96e5d-ad74-4c05-a9da-0c0c86106d80',
            'name' => 'Item3'
        ),
        (int) 3 => array(
            'id' => '4fc96e64-a110-4036-bea2-0c0c86106d80',
            'name' => 'Item4'
        )
    )

现在我可以从这个paginate调用得到相同的结果,除了添加0索引

$this->set('items', $this->paginate('Collection', array('Collection.id'=>$id)));

array(
    (int) 0 => array(

        'Collection' => array(
            'id' => '4fc923f5-0a58-453f-9507-0c0c86106d80',
            'name' => '<collection_name>'
        ),

        'Item' => array(
            (int) 0 => array(
                'id' => '4fc92403-000c-4ed2-9dae-0c0c86106d80',
                'name' => 'Item1'
            ),
            (int) 1 => array(
                'id' => '4fc9241b-35ec-4810-b511-0c0c86106d80',
                'name' => 'Item2'
            ),
            (int) 2 => array(
                'id' => '4fc96e5d-ad74-4c05-a9da-0c0c86106d80',
                'name' => 'Item3'
            ),
            (int) 3 => array(
                'id' => '4fc96e64-a110-4036-bea2-0c0c86106d80',
                'name' => 'Item4'
            )
      )
  )
);

我可以在返回的数组上执行array_shift但是分页不起作用。我可以尝试为此创建自定义paginate函数,但想知道是否有一种更简单的方法来使用我正在使用的标准paginate,因为它有我想要的数据,只是额外的第一个数组父元素[0]。

提前感谢任何建议。

1 个答案:

答案 0 :(得分:2)

<?php

// Don't pull in child data, we'll fetch that manually.
$this->Collection->contain(); // Assuming you have this behavior.

// Get the collection.
$collection = $this->Collection->find('first', $options);

// Conditions
$this->paginate['Item'] = array(
    'conditions' => array(
        'Item.collection_id' => $collection['Collection']['id'];
    )
);

// Get the items
$items = $this->paginate('Item');

// Return to original child model structure.
array_walk($items, function(&$v) { // Anonymous functions requires PHP 5.3
    $v = $v['Item'];
});

// Add it to the collection array.
$collection['Item'] = $items;

?>

这就是我在子模型上实现分页的方式。试一试,也可能适合你。

-A

相关问题