Cakephp Self refer Model不工作

时间:2014-07-25 16:37:57

标签: php cakephp cakephp-model

我有一张桌子

Medias:
    ID,
    PARENT_ID
    PATH
    TITLE

Items:
    ID
    medias
    Title
    description

模型

class ImageGallery extends AppModel {

    public $name = 'ImageGallery';
    public $useTable = "medias";

    var $belongsTo = array( 
        'Parent' => 
        array('className' => 'ImageGallery', 
            'foreignKey' => 'parent_id',
            'dependent' => false, 
        ), 
    );

    var $hasMany = array( 
        'Children' => 
        array('className' => 'ImageGallery', 
            'foreignKey' => 'parent_id',
            'dependent' => false,
        ), 
    ); 
}


class Item extends AppModel {

    public $useTable = "items";
    public $validate = array(
        'title' => array(
            'rule' => 'notEmpty'
        ),

    );

    public $belongsTo = array(

        'Gallery'   => array(
            'className' => 'ImageGallery', 
            'foreignKey'    =>  'medias'),
    );

    public $hasMany = array(
        'ItemMeta'  => array( 'className' => 'ItemMeta'),
    );
}

媒体表包含图库信息。图像存储在parent_id关系中。

当我请求Item->find('all');时,我只从Media表中获得一个条目,但我也希望得到它的所有孩子。 :(

我可以使用$this->ImageGallery->findById(10);来获得它的孩子,但我想用物品模型来获取它们。

1 个答案:

答案 0 :(得分:1)

使用可包含行为指定您希望查询获取的关联模型。 http://book.cakephp.org/2.0/en/core-libraries/behaviors/containable.html

$this->Item->find('all', array('contain' => array('ImageGallery' => array('Children'))));

如果你想要深入到孩子的水平,就像你想要得到树的其余部分一样,那么你需要写一些东西以递归方式取出孩子,孩子的孩子等等。或者您可以更改代码和模型以使用CakePHP的树行为。请参阅http://book.cakephp.org/2.0/en/core-libraries/behaviors/tree.htmlhttp://www.dereuromark.de/2013/02/17/cakephp-and-tree-structures/