cakephp habtm嵌套数据

时间:2012-10-15 14:56:29

标签: cakephp

我有一个HABTM关系,我想从产品表中得到类别表的嵌套数据,就像这个产品数组一样:

array(
    (int) 0 => array(
        'id' => (int) 1,
        'name' => 'a',
        'categories' => array(
            (int) 0 => array(
                'id' => (int) 1
            ),
            (int) 1 => array(
                'id' => (int) 2
            )
        )
    ),
    (int) 1 => array(
        'id' => (int) 2,
        'name' => 'b',
        'categories' => array(
            (int) 0 => array(
                'id' => (int) 1
            )
        )
    )
)

蛋糕可以吗?

编辑:我会尝试进一步解释我想做什么。

请耐心等待我,我是新来的蛋糕,我很难掌握它。

我有一个'产品'表:

    public $hasAndBelongsToMany = array(
        'Category' => array(
            'className' => 'Category',
            'joinTable' => 'categories_sculptures',
            'foreignKey' => 'sculpture_id',
            'associationForeignKey' => 'category_id',
            'unique' => 'keepExisting'
        )
    )

和类别表:

    public $hasAndBelongsToMany = array(
        'Sculpture' => array(
            'className' => 'Sculpture',
            'joinTable' => 'categories_sculptures',
            'foreignKey' => 'category_id',
            'associationForeignKey' => 'sculpture_id',
            'unique' => 'keepExisting'
        )
    );

和类别产品表:

    public $belongsTo = array(
    'Category' => array(
        'className' => 'Category',
        'foreignKey' => 'category_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    ),
    'Sculpture' => array(
        'className' => 'Sculpture',
        'foreignKey' => 'sculpture_id',
        'conditions' => '',
        'fields' => '',
        'order' => ''
    )
);

我想建立一个雕塑的视图表,并在每一行中显示每个雕塑所在的类别(可能不止一个)。由于我是新蛋糕,我不知道我会怎么做。如果我只是查询mysql,我可以使用group_concat或嵌套选择获取此信息,或者通过循环遍历第一个数组并通过雕刻键查询category_sculpture表并将结果添加到第一个数组来效率低下。但我想知道以最佳方式获得这个结果。

1 个答案:

答案 0 :(得分:0)

我找到了满足我需求的答案:

$this->Sculpture->recursive = 1;