CakePHP 与 Containable 中的 find('list') 相同的结果格式

CakePHP same result format as find('list') in Containable

我正在寻找一种方法,使使用 Containable 行为的查询结果的格式与 find('list') 结果相同。例如:

$this->ModelA->find('all', array(
    'contain' => array(
        'ModelB' => array(
            'ModelC' => array(
                // This does NOT work but I need ModelC's fields to be formatted as an associative array where IDs are keys and names are values
                'fields' => array('id' => 'name')
            )
        )
    )
));

注意:将递归设置为 1 或 2 而不是使用 Containable 不是 一个选项,除非没有可用的解决方案Containable.

$this->ModelA->行为->load('Containable');

$this->ModelA->find('all', array( 'contain' => 数组( 'ModelB' ,'ModelC'=>数组( 'fields' => 数组('id', 'name')) ) ) );

请确保您已创建模型关联

我不确定您能否以您想要的格式恢复 returned 包含的数据,但您可以在找到它后对其进行更改。 Cake 实际上从 find('list') 构建 return 的方式是使用 Hash::combine()。因此,您可以使用此更改 returned 数据,使数据外观列表成为 find('list') return:-

$data = [
    [
        'id' => 1,
        'name' => 'Foo'
    ],
    [
        'id' => 2,
        'name' => 'Bar'
    ]
];
$results = Hash::combine($data, '{n}.id', '{n}.name');

这会 return:-

[
    1 => 'Foo',
    2 => 'Bar'
]

不确定您的 find('all') 数据到底是什么样子,因为您没有提供关联,但我猜您可以这样做:-

foreach ($data as &$row) {
    $row['ModelB']['ModelC'] = Hash::combine(
        $row['ModelB']['ModelC'], 
        '{n}.id', 
        '{n}.name'
    );
}